我们需要编写一个包含三个参数的JavaScript函数,分别是:日,月和年。基于这三个输入,我们的函数应找到该日期的星期几。
例如:如果输入是-
day = 15, month = 8, year = 1993
输出结果
那么输出应该是-
const output = 'Sunday'
为此的代码将是-
const dayOfTheWeek = (day, month, year) => {
//JS月从0开始
return dayOfTheWeekJS(day, month - 1, year);
}
function dayOfTheWeekJS(day, month, year) {
const DAYS = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
];
const DAY_1970_01_01 = 4;
let days = day − 1;
while (month − 1 >= 0) {
days += daysInMonthJS(month − 1, year);
month −= 1;
}
while (year − 1 >= 1970) {
days += daysInYear(year − 1);
year −= 1;
}
return DAYS[(days + DAY_1970_01_01) % DAYS.length];
};
function daysInMonthJS(month, year) {
const days = [
31, // January
28 + (isLeapYear(year) ? 1 : 0), // Feb,
31, // March
30, // April
31, // May
30, // June
31, // July
31, // August
30, // September
31, // October
30, // November
31, // December
];
return days[month];
}
function daysInYear(year) {
return 365 + (isLeapYear(year) ? 1 : 0);
}
function isLeapYear(year) {
return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
}
console.log(dayOfTheWeek(15, 8, 1993));我们想计算距给定日期多少天。为此,我们可以从臭名昭著的Unix时间0(1970年1月1日至1日,星期四)开始,然后从此处开始-
计算整年的天数
计算不完整年份的月份中的天数
未完成月份的剩余天数
输出结果
控制台中的输出将是-
Sunday