有一个方便的方法可以比较时间间隔,将它们添加到 0 日期并比较日期。
<?php
function compare(DateInterval $first, DateInterval $second): int
{
$firstDate = (new DateTime())->setTimestamp(0)->add($first);
$secondDate = (new DateTime())->setTimestamp(0)->add($second);
return $firstDate <=> $secondDate;
}
echo compare(DateInterval('P2D'), new DateInterval('PT48H')) . PHP_EOL;
echo compare(DateInterval::createFromDateString('2 days'), DateInterval::createFromDateString('48 hours')) . PHP_EOL;
echo compare(DateInterval::createFromDateString('2 days'), DateInterval::createFromDateString('49 hours')) . PHP_EOL;
echo compare(DateInterval::createFromDateString('2 days'), DateInterval::createFromDateString('47 hours')) . PHP_EOL;
?>
输出
0
0
-1
1