Skip to content

Instantly share code, notes, and snippets.

@plindsay
Created March 30, 2017 21:01
Show Gist options
  • Save plindsay/77b05ae1ffba0696c8a01900ecb83984 to your computer and use it in GitHub Desktop.
Save plindsay/77b05ae1ffba0696c8a01900ecb83984 to your computer and use it in GitHub Desktop.
Loop through months, accounting for February
<?php
/*
based on this SO answer - http://stackoverflow.com/a/40877555/134823
*/
$addMonths = function ($date, $months) {
$orig_day = $date->format('d');
$date->modify('+'.$months.' months');
while ($date->format('d') < $orig_day && $date->format('d') < 5) {
$date->modify('-1 day');
}
};
$d = new \DateTime('-4 months');
$dates = [];
for ($i = 1; $i <= 4; $i++) {
$addMonths($d, 1);
$start = $d->format('Y-m-01');
$end = new \DateTime($d->format('Y-m-t'));
$end->modify('+1 day');
$dates[] = ['start' => $start, 'end' => $end->format('Y-m-d')];
}
echo "<pre>".print_r($dates, true)."</pre>";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment