Zeller’s Congruence

I was working on something a few weeks ago, and I needed to calculate the day of the week in PHP. I honestly thought it would be too hard. I thought there were too many variables: leap years, non leap years for years divisible by 400, and maybe something else I hadn’t thought of… As it turns out, it was quite simple really. Zeller to the rescue!
This wasn’t too hard to code, just be wary and make sure you keep everything at integer level, we don’t want to deal with fractions, as a fraction in several parts may add ‘one’ to the day value (it took me a while to find that!)

$d=date(“d”);
$m=date(“m”);
$y=date(“y”);
if($m<3)
{$m+=12;$y-=1;}
$y1=(int)$y / 100;
$y2=(int)$y % 100;
$w= ($d + 26 * ($m + 1) / 10 + $y2 +intval($y2/4) + intval($y1/4) +5 * intval ($y1)) % 7;
$wkday=array(“Saturday, “,”Sunday, “,”Monday, “,”Tuesday, “,”Wednesday, “,”Thursday, “,”Friday, “,”Saturday “);
?>

Calculated using “Zeller’s congruence”:

where:
* h is the day of the week (0 = Saturday, 1 = Sunday, 2 = Monday, …
* q is the day of the month
* m is the month (3 = March, 4 = April, 5 = May, …)
* K the year of the century (year mod 100).
* J is the century (actually int(year / 100) ) (For example, in 1995 the century would be 19, even though it was the 20th century.)

Join the Conversation

1 Comment

  1. I finally fixed my implementation of this code snippet. Although I knew about the integer problem (I even mentioned it in the post), I still hadn’t fixed it up. Well now I have :)

Leave a comment

Leave a Reply to dave Cancel reply