Skip to content

Instantly share code, notes, and snippets.

@king724
Created March 3, 2012 05:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save king724/1964564 to your computer and use it in GitHub Desktop.
Save king724/1964564 to your computer and use it in GitHub Desktop.
Find the dates of a repeating event
<?php
/**
* Find dates of repeating events between two dates
*/
function find_recurring_dates($start_date, $end_date, $repeat_days){
$start = new DateTime($start_date);
$end = new DateTime($end_date);
// Find the number of days inbetween
$interval = $start->diff($end);
$num_days = $interval->days;
$return = array();
// Loop through all days in between start and end dates (inclusive)
for ($i = 0; $i <= $num_days; $i++) {
// Get date from start date plus loop increment
$incremented_date = strtotime('+' . $i . 'days', strtotime($start_date));
// Numeric representation of the day of the week -- 0 (for Sunday) through 6 (for Saturday)
$date = date('w', $incremented_date);
// Check to see if its in the repeat days array
if (in_array($date, $repeat_days)) {
$return[] = date('Y-m-d', $incremented_date);
}
}
return $return;
}
/**
Input:
$start_date = '2012-03-02';
$end_date = '2012-03-31';
$repeat_days = array(1,3,5); // Mon/Wed/Fri
Output:
Array
(
[0] => 2012-03-02
[1] => 2012-03-05
[2] => 2012-03-07
[3] => 2012-03-09
[4] => 2012-03-12
[5] => 2012-03-14
[6] => 2012-03-16
[7] => 2012-03-19
[8] => 2012-03-21
[9] => 2012-03-23
[10] => 2012-03-26
[11] => 2012-03-28
[12] => 2012-03-30
)
*/
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment