如何在php中获取从开始时间到结束时间的总小时数


How to get the total hour from starting time to end time in php

如何获取从开始时间到结束时间的总小时数。

   $start_time = '11:00:00 PM'; // as of 07/08/2013
   $end_time   = '01:00:00 AM'; // as of 08/08/2013

那么输出应该是:

   $total = '02:00:00'; // 12 hour format

您可以将日期字符串转换为时间值,然后相减以获得两者之间的秒差,然后简单地除以3600以获得小时差:

$t1 = strtotime('2013-08-07 23:00:00');
$t2 = strtotime('2013-08-08 01:00:00');
$differenceInSeconds = $t2 - $t1;
$differenceInHours = $differenceInSeconds / 3600;

如果你想找出总时间,而你只有时间值,那么就去做这个//24小时格式

    for ($i = 0; $i < count($array); $i++) { //array contains your sorted times like [H:i]
        $a = $array[$i]. " " .date("Y/m/d");
        $array[$i] = $a;
    }
    
    $total=0;
    for ($i = count($array); $i>1; $i--){
        if ($array[$i-1] < $array[$i-2]){
            $array[$i-1] = strtotime("+1 day", strtotime($array[$i-1]));
            $z = "a";
        }
        $a = strtotime($array[$i-1]);
        $b = strtotime($array[$i-2]);
        $diff = $a - $b;    
        $hours = ceil($diff / (24*60));
        $total += date("H", $hours);
    }
if ($z == "a"){
    $total += date("H", ceil(strtotime($array[0]) / (24*60)));
}