查詢日期之間天數 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP