mj-y mj-y - 5 months ago 8
PHP Question

how to add two time variable in php

I want to add 2 time variable in php. I use below code but it returns a big number. how can I have a time like (15:20:00) at the end?

code :

$time1="10:00:00";
$time2="05:20:00";
$sum = strtotime($time1)+strtotime($time2);
echo date("H:i:s",$sum);


result:
15:20:00

Answer

Try something like :

    echo sum_the_time($time1, $time2); 

function sum_the_time($time1, $time2) {
  $times = array($time1, $time2);
  $seconds = 0;
  foreach ($times as $time)
  {
    list($hour,$minute,$second) = explode(':', $time);
    $seconds += $hour*3600;
    $seconds += $minute*60;
    $seconds += $second;
  }
  $hours = floor($seconds/3600);
  $seconds -= $hours*3600;
  $minutes  = floor($seconds/60);
  $seconds -= $minutes*60;
  return "{$hours}:{$minutes}:{$seconds}";
}
Comments