Skip to content

Instantly share code, notes, and snippets.

@andejoni89
Forked from zashme/splitByMonths.php
Last active March 2, 2025 17:30
Show Gist options
  • Save andejoni89/716097ebe9fbc1b33e3233ca47b12a24 to your computer and use it in GitHub Desktop.
Save andejoni89/716097ebe9fbc1b33e3233ca47b12a24 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] - ($i>=$count-1?0: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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment