我们需要编写一个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