top of page

1185. Day of the Week

Overall

Introduction

We know that one week have 7 days include Sunday, Monday, Tuesday, Wednesday, Thursday, Friday and Saturday. However, do you know how to calculate the day of the week?

​

We have different method to calculate the day of the week. One of them is Zeller's congruence. Zeller's congruence is an algorithm devised by Christian Zeller(1822 â€“ 1899) in the 19th century.

​

Zeller's congruence: 

let c as first two digit of year

let y as last two digit of year

w=(y+Math.floor(y/4)+Math.floor(c/4)-2*c+2*month+Math.floor((3*(month+1))/5)+day+1)%7

weekday=(w%7+7)%7

​

Weekday:

Sunday: 0

Monday: 1

Tuesday: 2

Wednesday: 3

Thursday: 4

Friday: 5

Saturday: 6

​

In addition, if the month is January or February, it should be considered as month 13th or month 14th of last year.(e.g. 2022/1/31 should be considered as 2021/13/31)

​

Problem Content

Given a date, return the corresponding day of the week for that date.

The input is given as three integers representing the day, month and year respectively.

Return the answer as one of the following values {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}.


Example 1:

Input: day = 31, month = 8, year = 2019 Output: "Saturday"

Example 2:

Input: day = 18, month = 7, year = 1999 Output: "Sunday"

Example 3:

Input: day = 15, month = 8, year = 1993 Output: "Sunday"


Constraints:

  • The given dates are valid dates between the years 1971 and 2100.

Concept

We use Zeller's congruence to to calculate the day of the week.

​

First of all, we set array week=["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; for the final outupt.

​

Next, we know that if the month is January or February, it should be considered as month 13th or month 14th of last year. Therefore we use if-condition to determent month is <=2 or not. If it is true, month+=12 and then year-=1.

​

Then, we should split the year as two value:

c=parseInt(year.toString().substring(0,2));

y=parseInt(year.toString().substring(2));

​

After that, we can calculate w=(y+Math.floor(y/4)+Math.floor(c/4)-2*c+2*month+Math.floor((3*(month+1))/5)+day+1)%7 now.

​

Finally, we return week[(w%7+7)%7] can return the day of the week from array week[].

Solve(Javascript)

/**
 * @param {number} day
 * @param {number} month
 * @param {number} year
 * @return {string}
 */
var dayOfTheWeek = function(day, month, year) {
    let week=["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    if(month<=2){
        month+=12;
       year-=1;
       }
    let c=parseInt(year.toString().substring(0,2));
    let y=parseInt(year.toString().substring(2));
    let w=(y+Math.floor(y/4)+Math.floor(c/4)-2*c+2*month+Math.floor((3*(month+1))/5)+day+1)%7

    return week[(w%7+7)%7];
};

bottom of page