PHP calc difference between time greater than 24 hours

后端 未结 1 413
一个人的身影
一个人的身影 2021-01-16 12:21

What is the best way to calculate the difference in time, when time is greater than 24 hours.

Example

$time1 = \'76:00:00\';
$time2          


        
相关标签:
1条回答
  • 2021-01-16 13:02

    Use \DateTime and \DateInterval to perform calculations:

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

    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.

    EDIT: The timezone should be specified as UTC to avoid daylight saving time issues.

    0 讨论(0)
提交回复
热议问题