2017-11-09 03:31
浏览 21


This question already has an answer here:

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);

图片转代码服务由CSDN问答提供 功能建议

此问题已经存在 这里有一个答案:

  • PHP找到两个日期时间之间的差异 6 answers \ n
  • HH的时差:MM:SS 格式 2 answers < / ul>

    我试图用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); 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • du7535 2017-11-09 03:36

    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');
    点赞 打赏 评论

相关推荐 更多相似问题