PHP计算时间差大于24小时

编程入门 行业动态 更新时间:2024-10-24 19:29:55
本文介绍了PHP计算时间差大于24小时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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:00 How 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 DateIntervals, 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小时

本文发布于:2023-10-30 22:52:32,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时间差   小时   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!