const isLeapYear = year => year % 4 === 0 && year % 100 !== 0 || year % 400 === 0
(year - 1971) * 365
(year - 1 - 1968) / 4 | 0
const daysFrom19710101 = year => (year - 1971) * 365 + (year - 1 - 1968) / 4 | 0
给你一个字符串 date ,按 YYYY-MM-DD 格式表示一个 现行公元纪年法 日期。返回该日期是当年的第几天。
var dayOfYear = function(date) {
const [year, month, day] = date.split('-')
const months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0) months[1] = 29
let days = 0
for (let i = 0; i < month - 1; i++) days += months[i]
return days + +day
};
replace(/-\d+-\d+/, '-01-01')
返回当前的 1 月 1 日,天数 +1
new Date().getTime()
返回自 1970/01/01 以来的毫秒数var dayOfYear = function(date) {
const dateBegin = date.replace(/-\d+-\d+/, '-01-01')
return (new Date(date).getTime() - new Date(dateBegin).getTime()) / 1000 / 86400 + 1 | 0
};
请你编写一个程序来计算两个日期之间隔了多少天。 日期以字符串形式给出,格式为 YYYY-MM-DD,如示例所示。
var daysBetweenDates = function(date1, date2) {
return Math.abs(getDaysTo1971(date1) - getDaysTo1971(date2))
};
const getDaysTo1971 = date => {
const [year, month, day] = date.split('-')
let days = 0
days += (year - 1971) * 365 + ((year - 1 - 1968) / 4 | 0)
const months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0) months[1] = 29
for (let i = 0; i < month - 1; i++) days += months[i]
return days + +day
}
var daysBetweenDates = function(date1, date2) {
return Math.abs(new Date(date1).getTime() - new Date(date2).getTime()) / 1000 / 86400 | 0
};