PHP 计算小时数

PHP calculating hours

以下代码无法正常工作,我很想知道为什么它无法正确计算:

$hours = date('H:i' , strtotime('03:00') - strtotime('02:00'));

echo $hours;

结果:02:00

预期结果:01:00

谁能帮我猜猜哪里出了问题?

02:00 as the result

您可能想要这样的东西:

$hours = date('H:i' , strtotime('03:00 - 02:00'));

甚至:

$hours = date('H:i' , strtotime('03:00 - 2 hours'));

这将打印 01:00

https://3v4l.org/on4JH

可以使用DateTime对象来完成:

$date1 = new DateTime('03:00');
$date2 = new DateTime('02:00');
$dateInterval = $date1->diff($date2);

echo $dateInterval->format('%H:%S'); // result would be 01:00