写一个方法计算两个给定时间的月份差、天数差、小时差

105 阅读1分钟

"```javascript function calculateTimeDifference(date1, date2) { const diffInMonths = Math.abs(date2.getMonth() - date1.getMonth()); const diffInDays = Math.abs((date2 - date1) / (1000 * 60 * 60 * 24)); const diffInHours = Math.abs((date2 - date1) / (1000 * 60 * 60));

return { months: diffInMonths, days: diffInDays, hours: diffInHours }; }

const date1 = new Date('2023-01-15'); const date2 = new Date('2023-03-20');

const timeDifference = calculateTimeDifference(date1, date2); console.log(timeDifference);