Skip to content

Instantly share code, notes, and snippets.

@zashme
Created February 6, 2015 16:47
Show Gist options
  • Save zashme/aa5c578ded5fc99aa65a to your computer and use it in GitHub Desktop.
Save zashme/aa5c578ded5fc99aa65a to your computer and use it in GitHub Desktop.
split date range into months ranges
<?php
function getMonthRanges($start, $end)
{
$timeStart = strtotime($start);
$timeEnd = strtotime($end);
$out = [];
$milestones[] = $timeStart;
$timeEndMonth = strtotime('first day of next month midnight', $timeStart);
while ($timeEndMonth < $timeEnd) {
$milestones[] = $timeEndMonth;
$timeEndMonth = strtotime('+1 month', $timeEndMonth);
}
$milestones[] = $timeEnd;
$count = count($milestones);
for ($i = 1; $i < $count; $i++) {
$out[] = [
'start' => $milestones[$i - 1],
'end' => $milestones[$i] - 1
];
}
return $out;
}
function applyFormat(&$item)
{
$item = date('Y-m-d H:i:s', $item);
}
$result = getMonthRanges('15-10-2014', '19-03-2015');
array_walk_recursive($result, 'applyFormat');
print_r($result);
@andejoni89
Copy link

andejoni89 commented Jul 6, 2022

thanks, this is what i need.
Awesome bro

Line 20: for me should be 'end' => $milestones[$i] - ($i>=$count-1?0:1)
full code https://gist.github.com/andejoni89/716097ebe9fbc1b33e3233ca47b12a24

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment