当时间大于24小时时,计算时间差的最佳方法是什么?
$time1 = '76:00:00'; $time2 = '30:00:00'; // result should be 46:00:00 echo date('H:i:s', strtotime($time1) - strtotime($time2));
但是这不能用这个来做,因为它超过了24小时。在数据库中我还保存了一个时间,如下所示:33:30:00如何在php我可以格式化它:十三点三十分
mtb9vblg1#
使用\DateTime和\DateInterval执行计算:
\DateTime
\DateInterval
$date1 = new \DateTime('now', new DateTimeZone('UTC')); $date2 = new \DateTime('now', new DateTimeZone('UTC')); $time1 = new \DateInterval('PT76H'); $time2 = new \DateInterval('PT30H'); $date1->add($time1); $date2->add($time2); $diff = $date1->diff($date2); echo ($diff->days * 24 + $diff->h) . $diff->format(':%I:%S');
说明:无法直接在DateInterval上执行计算,因此您必须创建日期作为计算的基础。然后将两个不同的间隔添加到当前日期,并计算它们之间的差值。diff()返回包含总天数的\DateInterval,您必须将总天数乘以24才能获得小时数,以及不构成完整天数的小时数。编辑:时区应指定为UTC,以避免夏令时问题。
DateInterval
diff()
lb3vh1jj2#
/** * Common method to diff between two time * * @param string $start * @param string $end * @return string */ public function diffTime($start, $end) { /* $start = '76:00:00'; */ /* $end = '30:00:00'; */ /* Get total time in Seconds */ $totalStartTimeSec = self::getTotalSeconds($start); $totalEndTimeSec = self::getTotalSeconds($end); /* Get difference time in Seconds */ $difference = abs($totalStartTimeSec - $totalEndTimeSec); $hours = floor($difference / 3600); $minutes = floor(($difference % 3600) / 60); $seconds = $difference % 60; $diffFormat = str_pad($hours, 2, '0', STR_PAD_LEFT). ":" . str_pad($minutes, 2, '0', STR_PAD_LEFT). ":" . str_pad($seconds, 2, '0', STR_PAD_LEFT); /* result $diffFormat is '46:00:00'; */ return $diffFormat; } /** * Get total time in Seconds * * @param string $time * @return array */ public function getTotalSeconds($time) { $timeArr = explode(':', $time); $allTime = []; if (isset($timeArr[0]) && $timeArr[0] > 24) { $greaterDuration = $timeArr[0]; while ($greaterDuration > 24) { $greaterDuration -= 24; $allTime[] = strtotime('24:00:00') - strtotime('00:00'); } if ($greaterDuration == 24 && ($timeArr[1] != '00' || $timeArr[2] != '00')) { $greaterDuration -= 24; $allTime[] = strtotime('24:00:00') - strtotime('00:00'); } $remainingTime = str_pad($greaterDuration, 2, '0', STR_PAD_LEFT) . ':' . $timeArr[1] . ':' . $timeArr[2]; $allTime[] = strtotime($remainingTime) - strtotime('00:00'); } else { $allTime[] = strtotime($time) - strtotime('00:00'); } return array_sum($allTime); }
谢谢!
2条答案
按热度按时间mtb9vblg1#
使用
\DateTime
和\DateInterval
执行计算:说明:无法直接在
DateInterval
上执行计算,因此您必须创建日期作为计算的基础。然后将两个不同的间隔添加到当前日期,并计算它们之间的差值。diff()
返回包含总天数的\DateInterval
,您必须将总天数乘以24才能获得小时数,以及不构成完整天数的小时数。编辑:时区应指定为UTC,以避免夏令时问题。
lb3vh1jj2#
谢谢!