查找两个日期之间的天数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
热门推荐
7 带清的简短祝福语
10 优秀男士祝福语大全简短
11 同事男生节祝福语简短
12 赠礼贺卡祝福语简短英文
13 俄语祝福语贺卡文案简短
14 护士辞职送行祝福语简短
15 新房开工吉日祝福语简短
16 对航母的祝福语简短
17 口才课期末祝福语简短
18 爱情祝福语大全 简短实际