Given that 18 May 2024 is a Saturday, how do you determine which day 1 May falls on without using new Date()?
Edit:
The answer I provided should work for all the programming languages that has index 0 as Sunday. Since I couldn’t find the answer in SO, I decided to craft this answer out so that it help future developers that may ask the following question.
The reason why I added "without new Date()" is to prevent SO users from answering new Date(2024, 4, 1).getDay()
which add a layer of process to handle. Other than the following answer, if there is a better algorithm, feel free to provide so that we can contribute to SO.
2
Answers
When you modulo the
cur_date
by 7, it will return the result to the earliest date that falls on Saturday which is 4. Afterwards, you deduct from the day itself (6 - 4) which will return 2 (Tuesday). To offset that, you will need to + 1.Below is an example of the May 2024 Calendar.
We know that there are 7 days:
we also know that May 18th is a Saturday, that is:
and we also know that May 18 – May 1 = 17 days
which is in the modulo class of 2, because -5 + 7 === 2, therefore, May 1st was on
days[2]
which was a Wednesday.But when will future May 1st dates will occur? If we ignored leap years, then the formula would be
days[(7 + ((2 + (numberOfYears * 365)) % 7)) % 7]
, (we modulo with 7, add 7 to the result and modulo with 7 again to handle negatives too), but we need to account for leap years too, which is every 4 years, like this: