Zeller's Algorithm: Day of the Week

Suppose we know the date as month, day and year. What day of the week do we have? One way to do this is a technique developed by Dr. Christian Zeller, a 19th Century German scholar.


The algorithm itself

The algorithm uses a number of variables, all type Integer.

Suppose we have Month (1-12), Day (1-31) and Year.

Now:

          If Month is 1 or 2 Then
            A = Month+10
            NewYear = Year - 1  
          Else
            A = Month-2
            NewYear = Year
          End If

          B = Day

          C = which year of the century (that is, Mod(NewYear, 100))

          D = which century (that is, NewYear / 100)

          W = (13 * A - 1) / 5

          X = C / 4

          Y = D / 4

          Z = W + X + Y + B + C - 2 * D

          R = Mod(Z, 7)

At this point, R is an Integer value between 0 and 6, inclusive:

          R = 0         Sunday
          R = 1         Monday
          R = 2         Tuesday
          R = 3         Wednesday
          R = 4         Thursday
          R = 5         Friday
          R = 6         Saturday


Examples

Suppose the date is December 2, 2009. Then:

          Month = 12

          Day = 2

          Year = 2009

so:

          A = 10

          B = 2

          C = 9

          D = 20

          W = (13 * 10 - 1) / 5 = 129 / 5 = 25

          X = 9 / 4 = 2
          
          Y = 20 / 4 = 5
 
          Z = 25 + 2 + 5 + 2 + 9 - 2 * 20 = 3

          R = Mod((1, 0) = 3

and R = 3 gives us Wednesday.

Suppose instead the date is January 18, 2010. Then:

          Month = 1

          Day = 18

          Year = 2010

so:

          A = 11

          B = 18

          C = 9

          D = 20

          W = (13 * 11 - 1) / 5 = 143 / 5 = 28

          X = 9 / 4 = 2

          Y = 20 / 4 = 5

          Z = 28 + 2 + 5 + 18 + 9 - 2 * 20 = 22

          R = Mod(22, 7) = 1

and R = 1 gives us Monday.


There is a Wikipedia article on this subject which presents a similar (though not identical) version of the algorithm.

Other people have invented their own algorithms to do the same thing. (Some such algorithms are shorter. They are not necessarily easier to understand).

This uses the Gregorian calendar, which is our current standard. There are other calendars in use in the world. As the Gregorian calendar was devised in 1582, fixing the cumulative errors of the preceding Julian calendar, it is not clear that Zeller's algorithm will work properly for dates before 1582.