Calculating Floating Holidays in PHP

Since I’ve spent so much time figuring out the best method for calculating floating holidays in PHP, I’ve decided to share this little function with everyone. I found the best calculation method and mixed it in with what I thought was a little more useful. Just feed in the needed parameters and you’re good to go!

  1. function ordinal_day($ord, $day, $month, $year) {
  2.     $targetDay = date("w", strtotime("next $day"));
  3.     $earliestDate = 1 + 7 * ($ord1);
  4.     $weekday = date("w", mktime(0, 0, 0, $month, $earliestDate, $year));
  5.    
  6.     if ($targetDay == $weekday) {
  7.         $offset = 0;
  8.     } else {
  9.         if ($targetDay < $weekday) {
  10.             $offset = $targetDay + (7$weekday);
  11.         } else {
  12.             $offset = ($targetDay + (7$weekday))7;
  13.         }
  14.     }
  15.    
  16.     // Calculate the actual date of the holiday
  17.     $holidayDate = mktime(0, 0, 0, $month, $earliestDate + $offset, $year);
  18.    
  19.     return $holidayDate;
  20. }

The parameters:

  • $ord – The number of days. Ex. “The fourth Thursday in November” (Thanksgiving)
  • $day – The short abbreviation of the day of the week. Ex. “Thu”
  • $month – The month in number form. Ex. “11″
  • $year – The year in four-digit form. Ex. 2007

8 Responses to “Calculating Floating Holidays in PHP”

  1. You’re such a smartie! :)

  2. Thanks man! Just what I was looking for.

  3. What about for Memorial Day… The LAST Monday in May?

  4. Thanks for sharing something very useful for everyone. I was trying get also PHP, ideas but couldn’t make good one. After getting your article regarding PHP, got easier web developing solution. Can we get other article regarding HTML or etc?

  5. echo strtotime(‘Fourth Thursday of November’);

  6. http://www.php.net/manual/en/datetime.formats.relative.php

  7. I guess, it comes down to 46321 simple choice!