Get date by position (ie. third Wednesday of January)
May 22, 2010 PHP Coding
In a recent project I needed to come up with code to calculate something like the first, second, third day of whatever month. Unfortunately the strtotime() function does not let you enter “third Wednesday of January” to calculate the date. This is where the code below works great for such things.
function GetDayByPosition($Position, $Weekday, $Month, $Year) { // Sanatize some of the inputs $Position = strtolower($Position); $Weekday = strtolower($Weekday); // Go to next month so we can then go back 1 week at end of script for calculating last xxx of month if ($Position=='last') { $Month += 1; } // We cannot have 13 months so set as January of the next year. // This was pointed out by Evan who made a comment on the posting of this script if ($Month > 12) { $Month = 1; $Year += 1; } // Create new date object for the first of the month $D = new DateTime($Year.'-'.$Month.'-1'); $DOW = $D->format('w'); // Get the current day of the week based on the 1st of the month $keys = array('sunday'=>0,'monday'=>1,'tuesday'=>2,'wednesday'=>3, 'thursday'=>4,'friday'=>5,'saturday'=>6); // Calculate what the offset is based on the current day of the week // vs the day in the week you want to get $offset = $keys[$Weekday] - $DOW; if ($offset<0) { $offset += 7; } switch ($Position) { // Don't need to add anything to first case 'second': $offset += 7; // Add 1 week break; case 'third': $offset += 14; // Add 2 weeks break; case 'fourth': $offset += 21; // Add 3 weeks break; case 'last': $offset -= 7; // Go back 7 days break; } // Add the current offset of days to the date object $D->modify('+'.$offset.' days'); return $D->format('Y-m-d'); }
Usage:
// This will output 2009-01-05 echo 'First Monday of January 2009: ',GetDayByPosition('first', 'monday', 1, 2009),'<br />'; // This will output 2009-01-13 echo 'Second Tuesday of January 2009: ',GetDayByPosition('second', 'tuesday', 1, 2009),'<br />'; // This will output 2009-01-21 echo 'Third Wednesday of January 2009: ',GetDayByPosition('third', 'wednesday', 1, 2009),'<br />'; // This will output 2009-01-22 echo 'Fourth Thursday of January 2009: ',GetDayByPosition('fourth', 'thursday', 1, 2009),'<br />'; // This will output 2009-01-30 echo 'Last Friday of January 2009: ',GetDayByPosition('last', 'friday', 1, 2009),'<br />';
This can be used in a recurring calendar events page to allow similar event creation like the recurring events in Microsoft Outlook or any other popular calender applications.
Leave a Reply