计算错误的时间超过30分钟


Wrong time calculated having more than 30min

我有一个有点奇怪的问题,我有这个代码,在输出时,如果第二次有30分钟或更长时间,它总是增加一个小时。

$time1 = '12:00';
$time2 = '13:30';
list($hours, $minutes) = explode(':', $time1);
$startTimestamp = mktime($hours, $minutes);
list($hours, $minutes) = explode(':', $time2);
$endTimestamp = mktime($hours, $minutes);
$seconds = $endTimestamp - $startTimestamp;
$minutes = ($seconds / 60) % 60;
$hours = round($seconds / (60 * 60));

这里发生了什么事?

记住数学。将区间[0.5;1)中的所有内容四舍五入等于1。

round(0.5) = 1

这就是为什么你在[30;60]中有+1小时的时间。

不使用round,而是使用intval作为$seconds / (60 * 60)表达式始终返回浮点值,并且我们只需要该结果的整数部分