Nov 19

You can use the Calendar class to get the day of the week for a particular date. But if you’re after an algorithm to do the same then Zeller’s congruence may be of interest to you.

Zeller’s congruence is an algorithm devised by Christian Zeller to calculate the day of the week for any Julian or Gregorian calendar date.

Here’s an implementation of the Zeller algorithm in Java.


Calendar today = Calendar.getInstance();
int day = today.get(Calendar.DATE);
int month = today.get(Calendar.MONTH) + 1;
int year = today.get(Calendar.YEAR);

if (month < 3) {
    month += 12;
    year -= 1;
}

int k = year % 100;
int j = year / 100;

// 0 = Saturday, 1 = Sunday, ...
int dayOfWeek = ((day + (((month + 1) * 26) / 10) + 
   k + (k / 4) + (j / 4)) + (5 * j)) % 7;

Hope this helps you implement Zeller in Java.

written by objects \\ tags: , , , , ,