Calculate difference between 2 times in hours in PHP

后端 未结 7 702
無奈伤痛
無奈伤痛 2020-12-10 20:11

I have two times - For eg- the current time - 08:24 and date is 02/01/2013 in dd/mm/yyyy format and I have another time at 13:46 and date is 31/12/2012 . So, how can I cal

7条回答
  •  执念已碎
    2020-12-10 20:18

    Another way is to use PHP's date-related classes. The example below uses DateTime::diff() to get a DateInterval object ($interval). It then uses the interval's properties to arrive at the total number of hours in the interval.

    $a = DateTime::createFromFormat('H:i d/m/Y', '08:24 02/01/2013');
    $b = DateTime::createFromFormat('H:i d/m/Y', '13:46 31/12/2012');
    
    $interval = $a->diff($b);
    $hours    = ($interval->days * 24) + $interval->h
              + ($interval->i / 60) + ($interval->s / 3600);
    
    var_dump($hours); // float(42.633333333333)
    

提交回复
热议问题