- Doomsday algorithm in C language
The doomsday rule or doomsday algorithm is a way of calculating the day of the week of a given date. It provides a perpetual calendar because the Gregorian calendar moves in cycles of 400 years.
- Determine the
"anchor day"for the century.
- Use the anchor day for the century to calculate the doomsday for the year.
- Choose the closest date out of the ones that always fall on the doomsday. (e.g. 4/4, 6/6, 8/8), and count the number of days (modulo 7, %7 in C) between that date and the date in question to arrive at the date of the week.
Here are the list of doomsday standard for years.
1800~1899 is Friday
1900~1999 is Wednesday
2000~2099 is Tuesday
2100~2199 is Sunday
Then it loops
Using the data above, we can calculate a doomsday of the year we choose.
For example I will choose 2016 03 24 Formatted as YYYYMMDD.
- Divide last two digits of Year with 12 - YYYY -> YYYY / 12 -> a…b
2016-> 16/12 = 1 ... 4 as remainder ( a is 1 and b is 4 )
- Divide the remainder with 4 ->
4/4 = 1 (c is 1)
- Anchor day can be calculated with list above with YYYY and add a+b+c on the anchor day.
2016 will be between 2000~2099, Tuesday.
a+b+c = 1 + 4 + 1 = 6
Now add result from 2 on Tuesday. Which will be Tuesday + 6 = Monday.
2016's doomsday is Monday
Now we know 2016’s doomsday is on Monday. Then we can simply calculate the difference in date between doomsday and the day we want to know, to calculate the day.
Using the example above, 2016 03 24, we know 2016’s doomsday is on Monday and I will use February 29th for my doomsday since it’s a leap year.
Days until February 29th are 60 days and days until 24th of March is 84 days. Now we can calculate the day with the function I wrote on the program.
dayOfWeek = ((doomsday + DAYS_PER_WEEK) - (DAYS_PER_WEEK + ((daysToEndOfFeb - daysToInputDay) % DAYS_PER_WEEK))) % DAYS_PER_WEEK;
This will give me a day of week with leap year case.
dayOfWeek = ((4 + 7) - (7 + ((60 - 84) % 7))) % 7;
= ((11) - (7 + (-3))) % 7;
= 7 % 7
You can download sample C file from HERE