abhishek bagul abhishek bagul - 7 months ago 18
PHP Question

Calculating the total time by adding the time intervals

I have got the verious time intervals in H:i:s format like shown below:

$interval1 = 12:15:33;
$interval2 = 0:36:10;
$interval3 = 0:1:30;


Now i want to add all this intervals together like

$total = $interval1 + $interval2 + $interval3;


Here is my php code

function addinterval($x,$y){
$x = explode(':', $x);
$y = explode(':', $y);
$seconds = $minit = $hours = 0;

$seconds = $x[2] + $y[2];
if($seconds > 60){
$seconds = $seconds - 60;
$minit = $minit + 1;
}
$minit = $minit + $x[1] + $y[1];
if($minit > 60){
$minit = $minit - 60;
$hours = $hours + 1;
}
$hours = $hours + $x[0] + $y[0];
return $hours. ':' . $mint . ':' . $seconds;
}



$first = addinterval('12:15:33','0:36:10');
echo 'The result :' . $first;
$second = addinterval($first, '0:1:30');
echo 'The final result' . $second;

Answer

Use strtotime().

$interval1 = 12:15:33;
$interval2 = 0:36:10;
$interval3 = 0:1:30;

$total = strtotime($interval1) +  strtotime($interval2) +  strtotime($interval3) -strtotime("today");

$time =date("H:i:s", $total);

Output

12:51:43

Online Demo : Click Here

Comments