Chúng ta cần viết một hàm JavaScript nhận vào hai ngày ở định dạng 'YYYY-MM-DD' làm đối số thứ nhất và thứ hai. Hàm sẽ tính và trả về số ngày giữa hai ngày đó.
Ví dụ:
Nếu các ngày đầu vào là:
const str1 = '2020-05-21'; const str2 = '2020-05-25';
Thì đầu ra sẽ là:
const output = 4;
Ví dụ
const str1 = '2020-05-21';
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));Kết quả
Kết quả hiển thị trong console sẽ là:
4