js计算两日期相差的天数、月数
时间: 2024-06-14 18:07:11 浏览: 149
在JavaScript中,可以使用Date对象和一些简单的计算来计算两个日期之间的天数和月数。
1. 计算两个日期之间的天数:
```javascript
function getDaysDiff(date1, date2) {
const oneDay = 24 * 60 * 60 * 1000; // 一天的毫秒数
const diffDays = Math.round(Math.abs((date1 - date2) / oneDay));
return diffDays;
}
const startDate = new Date('2021-01-01');
const endDate = new Date('2021-01-10');
const daysDiff = getDaysDiff(startDate, endDate);
console.log("Days difference:", daysDiff); // 输出:9
```
2. 计算两个日期之间的月数:
```javascript
function getMonthsDiff(date1, date2) {
const diffMonths = (date2.getFullYear() - date1.getFullYear()) * 12 + (date2.getMonth() - date1.getMonth());
return diffMonths;
}
const startDate = new Date('2021-01-01');
const endDate = new Date('2021-03-01');
const monthsDiff = getMonthsDiff(startDate, endDate);
console.log("Months difference:", monthsDiff); // 输出:2
```
阅读全文