3v4l.org

run code in 300+ PHP versions simultaneously
<?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; }
Output for 7.4.0 - 7.4.33, 8.0.1 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.25, 8.4.1 - 8.4.12
2022-10-04 - 2022-11-04 : 1 Month Ok<br> 2020-10-04 - 2022-11-04 : 25 Month Ok<br> 2022-11-04 - 2020-10-04 : -25 Month Ok<br> 2021-10-04 13:00 - 2022-11-04 13:00 : 13 Month Ok<br> 2021-10-04 13:00 - 2022-11-04 12:59 : 12 Month Ok<br> 2021-10-04 13:01 - 2022-11-04 13:00 : 12 Month Ok<br> 2022-11-01 13:00 Europe/Berlin - 2022-12-01 12:00 UTC : 1 Month Ok<br>

preferences:
92.44 ms | 407 KiB | 5 Q