我使用以下代码计算时间差
$estimated_time = '40:30';
$completed_time = '20:45';
// list the times
list($hours1, $minutes1) = explode(':', $estimated_time);
list($hours2, $minutes2) = explode(':', $completed_time);
// mktime
$t1 = mktime($hours1, $minutes1); // estimated time
$t2 = mktime($hours2, $minutes2); // completed time
// Calc the difference in seconds
$seconds = $t1 - $t2;
// hours
$hours = floor($seconds / (60*60));
// minutes
$minutes = floor(($seconds / 60) % 60);
// result 19:45
echo $diff = $hours . ':' . $minutes;
此计算有效,因为预计会有19:45。问题是当我像这样改变时间时
// expected 4:30 extra hours but result is -5:30
// this is caused by the floor method but if I remove the floor
// method the positive value is not working correctly
$estimated_time = '40:00';
$completed_time = '44:30';
结果为-5:-30。这是由于地板造成的。如何正确地使用正值和负值。这也是用时间计算的正确方法。
我曾尝试使用DateTime但它无法处理大于24的小时
解决 感谢@Mad Dog PHP calc difference between time greater than 24 hours
$estimated_time = '40:30';
$completed_time = '20:55';
// invert
// 0 => positive
// 1 => negative
// list the times
list($hours1, $minutes1) = explode(':', $estimated_time);
list($hours2, $minutes2) = explode(':', $completed_time);
$date1 = new DateTime('now', new DateTimeZone('UTC'));
$date2 = new DateTime('now', new DateTimeZone('UTC'));
$time1 = new DateInterval('PT'.$hours1.'H'.$minutes1.'M');
$time2 = new DateInterval('PT'.$hours2.'H'.$minutes2.'M');
$date1->add($time1);
$date2->add($time2);
$diff = $date2->diff($date1);
$result = ($diff->days * 24 + $diff->h) . $diff->format(':%I');
if($diff->invert == 0){
echo $result;
} else {
echo 0 . ' (extra time: '.$result.')';
}