有一种方便的方法可以通过将间隔添加到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(new 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