Skip to content

Instantly share code, notes, and snippets.

@plasticbrain
Last active November 13, 2015 22:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plasticbrain/67e6e905ee7559d2a9c2 to your computer and use it in GitHub Desktop.
Save plasticbrain/67e6e905ee7559d2a9c2 to your computer and use it in GitHub Desktop.
PHP - Calculate the next occurrence of a given date
<?php
// Usage
$occurrences = next_occurrence('Friday', 13);
foreach($occurrences as $day) {
echo $day->format('D M j, Y') . PHP_EOL;
}
/**
* Find the next occurrence(s) of a given date
*
* @param string $day_name The full name of the day (Monday-Friday)
* @param integer $day_num The day number (1-31)
* @param string $month_name [optional] The abbreviated month name (Jan-Dec)
* @param integer $num_occurrences The number of occurrences to show
* @return array All of the occurrences
*
*/
function next_occurrence($day_name='Friday', $day_num=13, $month_name=null, $num_occurrences=20)
{
$first_day = new DateTime($day_name);
// Calculate the end date
// note: use "clone" first because "modify" changes the original instance
$last_day = clone $first_day;
$last_day->modify("+$num_occurrences years");
// Select the format based on whether or not the month is included
if (is_null($month_name)) {
$format = 'l j';
$long_format = "$day_name $day_num";
} else {
$format = 'M l j';
$long_format = "$month_name $day_name $day_num";
}
// Iterate over each day for the next $num_occurrences, and see if the date matches the given format
$dates = array();
while($first_day < $last_day) {
if($first_day->format($format) == $long_format) {
$dates[] = clone $first_day;
}
$first_day->modify('+7 days');
}
return $dates;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment