Reputation: 8509
I am trying to add two time values A and B where A = 18:00:00 which is an actual time and B = 00:45:00 which is just a time duration. By adding A and B the expected result should be 18:45:00 but for some reason I always get a wrong value.
$newTime = date('H:i:s', strtotime($row->start_time) + strtotime($row->quiz_duration));
Upvotes: 1
Views: 84
Reputation: 8960
Try this:
<?php
function time_to_interval($time) {
$parts = explode(':',$time);
return new DateInterval('PT'.$parts[0].'H'.$parts[1].'M'.$parts[2].'S');
}
function add_intervals($a,$b) {
$zerodate = new DateTime('0000-01-01 00:00:00');
$dt = clone $zerodate;
$dt->add($a);
$dt->add($b);
return $zerodate->diff($dt);
}
function format_interval_hhmmss($interval){
$totalhours = $interval->h + ($interval->d * 24);
return $totalhours.$interval->format(':%I:%S');
}
$interval1 = time_to_interval('18:00:00');
$interval2 = time_to_interval('00:45:00');
$interval3 = add_intervals($interval1,$interval2);
echo format_interval_hhmmss($interval3);
Demo:
http://3v4l.org/MlTs5
Alternative:
function addtime($time1,$time2)
{
$x = new DateTime($time1);
$y = new DateTime($time2);
$interval1 = $x->diff(new DateTime('00:00:00')) ;
$interval2 = $y->diff(new DateTime('00:00:00')) ;
$e = new DateTime('00:00');
$f = clone $e;
$e->add($interval1);
$e->add($interval2);
$total = $f->diff($e)->format("%H:%I:%S");
return $total;
}
echo addtime('18:00:00','00:45:00');
Demo:
http://3v4l.org/A6m1A
Upvotes: 1