Finding day of week from date (day, month, year) in JavaScript



We are required to write a JavaScript function that takes in three argument, namely:day, month and year. Based on these three inputs, our function should find the day of the week on that date.

For example: If the inputs are −

day = 15, month = 8, year = 1993

Output

Then the output should be −

const output = 'Sunday'

Example

The code for this will be −

const dayOfTheWeek = (day, month, year) => {    // JS months start at 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));

Explanation

We want to count how many days until the given date. To do so, we can start at the infamous Unix time 0 (Thursday 1970−01−01) and go from there −

  • Count days in complete years

  • Count days in month for the incomplete year

  • Remaining days for the incomplete month

Output

And the output in the console will be −

Sunday
Updated on: 2020-11-20T13:28:11+05:30

721 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements