前端计算两个日期相差几天 , 并把相差的这几天数组输出
时间: 2024-05-02 18:23:36 浏览: 105
我可以为您提供计算两个日期相差几天的代码,代码如下:
```javascript
function getDateRange(startDate, endDate) {
var dateArray = new Array();
var currentDate = startDate;
while (currentDate <= endDate) {
dateArray.push(new Date(currentDate));
currentDate.setDate(currentDate.getDate() + 1);
}
return dateArray;
}
function getDaysBetween(startDateString, endDateString) {
var startDate = new Date(startDateString);
var endDate = new Date(endDateString);
var oneDay = 24*60*60*1000;
var diffDays = Math.round(Math.abs((startDate.getTime() - endDate.getTime())/(oneDay)));
var dateRange = getDateRange(startDate, endDate);
var daysArray = dateRange.map(function(date){
return date.toISOString().slice(0,10);
});
return {
'diffDays': diffDays,
'daysArray': daysArray
};
}
```
您只需调用 `getDaysBetween` 函数,传入两个日期字符串参数即可,例如:
```javascript
getDaysBetween('2022-01-01', '2022-01-10')
```
得到输出结果:
```json
{
"diffDays": 9,
"daysArray": [
"2022-01-01",
"2022-01-02",
"2022-01-03",
"2022-01-04",
"2022-01-05",
"2022-01-06",
"2022-01-07",
"2022-01-08",
"2022-01-09",
"2022-01-10"
]
}
```
其中 `diffDays` 表示相差的天数,`daysArray` 表示相差的日期数组。
阅读全文