问题描述
What is the best way to calculate the difference in time, when time is greater than 24 hours.
$time1 = '76:00:00';
$time2 = '30:00:00';
// result should be 46:00:00
echo date('H:i:s', strtotime($time1) - strtotime($time2));
但这不能完成,因为它超过24小时。
But this could not be done with this because its greater then 24 hours.
另外在数据库中我已经存储了一个这样的时间:33:30:00
如何将PHP格式化为:33:30
Also in a database i've stored a time like this: 33:30:00How in php could i format it to: 33:30
推荐答案
使用 \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
s,所以你必须创建日期作为计算的基础。然后为当前日期添加两个不同的间隔,并计算它们之间的差异。 diff()
返回 \DateInterval
,其中包含总天数,您必须乘以24才能获得小时数,并且没有整整一天的时间。
Explanation:It's not possible to perform calculations directly on DateInterval
s, so you have to create dates as a basis for calculations. Then add two different intervals to current dates, and calculate a difference between them. diff()
returns \DateInterval
that contains total number of days, that you have to multiply by 24 to get hours, and hours that don't make full days.
编辑:时区应指定为UTC,以避免夏令时问题。
The timezone should be specified as UTC to avoid daylight saving time issues.
这篇关于PHP计算时间差大于24小时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!