<?php
function diffInMonth(DateTime $start,DateTime $end): int {
$endDate = (clone $end)->setTimeZone($start->getTimeZone());
list($yearStart,$monthStart,$dayStart) = explode(" ",$start->format("Y m dHis"));
list($yearEnd,$monthEnd, $dayEnd) = explode(" ",$endDate->format("Y m dHis"));
$mothDiff = ($yearEnd - $yearStart) * 12 + $monthEnd - $monthStart;
if($dayStart > $dayEnd && $end >= $start) --$mothDiff;
elseif($dayStart < $dayEnd && $end < $start) ++$mothDiff;
return $mothDiff;
}
$tests = [
['start' => '2022-10-04', 'end' => '2022-11-04', 'month' => 1],
['start' => '2020-10-04', 'end' => '2022-11-04', 'month' => 25],
['start' => '2022-11-04', 'end' => '2020-10-04', 'month' => -25],
['start' => '2021-10-04 13:00', 'end' => '2022-11-04 13:00', 'month' => 13],
['start' => '2021-10-04 13:00', 'end' => '2022-11-04 12:59', 'month' => 12],
['start' => '2021-10-04 13:01', 'end' => '2022-11-04 13:00', 'month' => 12],
['start' => '2022-11-01 13:00 Europe/Berlin', 'end' => '2022-12-01 12:00 UTC', 'month' => 1],
];
foreach($tests as $test){
$start = new DateTime($test['start']);
$end = new DateTime($test['end']);
$month = diffInMonth($start, $end);
$msg = $test['start']." - ".$test['end'];
$msg .= ' : '.$month.' Month '.($month === $test['month'] ? 'Ok' : 'Error')."<br>\n";
echo $msg;
}
preferences:
24.32 ms | 404 KiB | 5 Q