about me

projects

MPEG & DVD

doc

leisure

Sam Hocevar’s .plan

This is an experimental blog engine. RSS feeds: everything | blog | Debian (DPL only) | VideoLAN | GNOME | Mono

Finding a specific instance of a given day in the month in PHP

Posted on Thu, 10 Nov 2005 23:30:17 +0100 - Keywords: debian, devel

Andrew: to work out the fourth Thursday of the month, use this instead:

function nth_day($instance, $dow, $month, $year)
{
  $first_dom = date("w", mktime(0, 0, 0, $month, 1, $year));
  return 1 + ((7 + $dow - $first_dom) % 7) + 7 * ($instance - 1);
}

Or, using Zeller’s rule and avoiding function calls:

function nth_day($instance, $dow, $month, $year)
{
  if($month < 3) { $year--; } $D = $year % 100; $C = (int)($year / 100); $m = 1 + (($month + 9) % 12);
  $f = 1 + (int)((13 * $m - 1) / 5) + $D + (int)($D / 4) + (int)($C / 4) - 2 * $C;
  $first_dom = $f % 7;
  return 1 + ((7 + $dow - $first_dom) % 7) + 7 * ($instance - 1);
}

Update: thanks to Andrew for spotting the error in the second version. Due to my misunderstanding of a hack in Zeller’s rule, I had forgotten to decrease the year when the month was January or February. Also, PHP was not doing proper integer divisions and I had to cast results back to int despite all operands being ints.

Show the last 10 | 20 | 50 entries.