get difference in time in HH:MM format php

后端 未结 2 1753
灰色年华
灰色年华 2020-12-20 21:44

how can i get this to output

HH:MM format?

 $to_time = strtotime(\"2008-12-13 10:42:00\");  <--AM
 $from_time = strtotime(\"2008-12-14 8:21:00\")         


        
2条回答
  •  暖寄归人
    2020-12-20 22:26

    Firstly, 8:21:00 will be interpreted as 8AM unless you specified otherwise using DateTime::createFromFormat().

    To work out time differences, use DateTime::diff():

    $to = new DateTime("2008-12-13 10:42:00");
    $from = new DateTime("2008-12-14 8:21:00");
    
    $stat = $to->diff($from); // DateInterval object
    
    echo $stat->format('%Hh:%Im');
    

    This will display the hour/minute difference between the two times, but only up to 24 hours.

    If you need more than 24 hours, you should do the following:

    $hours   = $stat->days * 24 + $stat->h;
    $minutes = $stat->i;
    
    printf('%02sh:%sm', $hours, $minutes);
    

提交回复
热议问题