查找两个日期之间的天数JavaScript
我们需要编写一个JavaScript函数,该函数以'YYYY-MM-DD'格式分别接受两个日期作为第一个和第二个参数。然后,该函数应计算并返回两个日期之间的天数。
例如-
如果输入日期是-
const str1 = '2020-05-21'; const str2 = '2020-05-25';
那么输出应该是-
const output = 4;
示例
const str2 = '2020-05-25';
const daysBetweenDates = (str1, str2) => {
const leapYears = (year, month) => {
if (month <= 2){
--year;
};
let floor = Math.floor;
return floor(year / 400) + floor(year / 4) - floor(year / 100);
};
let monthDays = [0, 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30];
for (let i = 1; i < monthDays.length; ++i){
monthDays[i] += monthDays[i - 1];
};
let days = (year, month, d) => (year * 365) + leapYears(year, month) + monthDays[month] + d; let p = days(...str1.split('-').map(Number));
let q = days(...str2.split('-').map(Number));
return Math.abs(p - q);
};
console.log(daysBetweenDates(str1, str2));输出结果
控制台中的输出将是-
4
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短