得到时间差H:mm:ss格式[重复](Get the time difference in H:mm:ss format [duplicate])

编程入门 行业动态 更新时间:2024-10-26 02:29:18
得到时间差H:mm:ss格式[重复](Get the time difference in H:mm:ss format [duplicate])

这个问题在这里已经有了答案:

PHP找到两个日期时间 3个答案 之间的区别 时差:HH:MM:SS格式 2个答案

我试图找到使用PHP格式H:mm:ss两个时间值之间的时间差。

当我尝试使用以下代码时,我得到了差异01:00:20而不是00:00:20 。 我的代码有什么问题?

$start_time = strtotime("0:17:14"); $end_time = strtotime("0:17:34"); $diff = $end_time - $start_time; echo date('H:i:s', $diff);

This question already has an answer here:

PHP find difference between two datetimes 6 answers time difference in HH:MM:SS format 2 answers

I am trying to find the time difference between two time values in the format H:mm:ss using PHP.

When I tried with the following code, I'm getting the difference 01:00:20 instead of 00:00:20. What's wrong with my code?

$start_time = strtotime("0:17:14"); $end_time = strtotime("0:17:34"); $diff = $end_time - $start_time; echo date('H:i:s', $diff);

最满意答案

您的$diff变量不是时间戳,而是持续时间/间隔。 date()函数用于格式化时间戳,并且不会像您所期望的那样正确处理间隔。

相反,尝试使用DateTime类来读取您的时间戳,并使用DateTime::diff()将它们之间的差异转换为DateInterval 。 然后,您可以使用DateInterval::format来获取所需的输出。

像这样的东西应该工作:

$start_time = new DateTime("0:17:14"); $end_time = new DateTime("0:17:34"); $diff = $end_time->diff($start_time); echo $diff->format('%H:%I:%S');

Your $diff variable is not a timestamp, it's a duration/interval. The date() function is intended to format timestamps, and won't properly handle intervals like you're expecting.

Instead, try using the DateTime class to read your timestamps, and turn the difference between them into a DateInterval using DateTime::diff(). You can then use DateInterval::format to get the output you want.

Something like this should work:

$start_time = new DateTime("0:17:14"); $end_time = new DateTime("0:17:34"); $diff = $end_time->diff($start_time); echo $diff->format('%H:%I:%S');

更多推荐

PHP,difference,$start_time,使用,之间,电脑培训,计算机培训,IT培训"/> <meta name=&q

本文发布于:2023-07-25 05:35:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1256716.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时间差   格式   ss   mm   duplicate

发布评论

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

>www.elefans.com

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