exupero's blog
RSSApps

Calculating a date's day of the week

In the previous post we calculated which day of the week certain memorable dates fall on in a given year. To find the day of the week for any given date that year, we subtract a doomsday date, find the remainder after dividing by seven, convert from a number to a day of the week, and add the year's anchor day.

Let's try, as a random example, October 27, 1913:

  1. The reference date for October is October 10
  2. 27 minus 10 is 17
  3. 17 modulo 7 is 3
  4. October 27 is 3 days after any year's anchor day
  5. The anchor day for 1913 is Friday (5)
  6. 5 plus 3 is 8
  7. October 27, 1913 was a Monday

It's preferable to know a reference date for each month to avoid cross-month calculations.

I've also found that having earlier dates avoids extra calculations. To illustrate why, consider October 2, which falls eight days before October's reference date of the 10th. It's tempting to take 8 modulo 7, but order matters, so we actually need to find -8 modulo 7. To take modulo 7 of negative numbers, add sevens: -8 modulo 7 is the same as -1 modulo 7 is the same as 6. The later a month's reference date is, the more often a random date will fall before it and you'll need to find the modulo of a negative number; not difficult, but extra work.