1

How can I get the total hour from start time to end time.

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

Then output should be:

   $total = '02:00:00'; // 12 hour format
rene
  • 41,474
  • 78
  • 114
  • 152
leonardeveloper
  • 1,813
  • 1
  • 34
  • 58
  • This link might have the solution you're looking for: http://stackoverflow.com/questions/5463549/subtract-time-in-php – sgbj Aug 07 '13 at 23:59
  • Date::diff is not accurate. When i have the given above it gives me wrong output – leonardeveloper Aug 08 '13 at 00:02
  • Are you restricted to only supplying the hours? If you can supply the dates along with the times then it'll output the result you're looking for. Ex: echo date_create('07/08/2013 11:00:00 PM')->diff(date_create('08/08/2013 01:00:00 AM'))->format('%h'); – sgbj Aug 08 '13 at 00:08
  • yes. I use timepicker only the date is not included. – leonardeveloper Aug 08 '13 at 00:23

2 Answers2

2

You can convert the date strings to time values, then subtract to get the difference in seconds between the two, then simply divide by 3600 to get the difference in hours:

$t1 = strtotime('2013-08-07 23:00:00');
$t2 = strtotime('2013-08-08 01:00:00');
$differenceInSeconds = $t2 - $t1;
$differenceInHours = $differenceInSeconds / 3600;
mti2935
  • 11,465
  • 3
  • 29
  • 33
0

If you want to find out the total time and you only have time values go for this. //24 hour format

    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)));
}
Knaggi
  • 1
  • 1