lilmer Posted May 26, 2014 Share Posted May 26, 2014 Good day, I have problem on subtracting time. Can anyone give me a hint how will I going to do that. I already manage to get the SUM on time addition using this method. $data = array('1:52:37','9:56:39','08:04:22','05:32:20'); echo convertTime($data); - ANSWER 25:25:58 function convertTime($data){ $seconds = null; $minutes = null; $hours = null; foreach($data as $key => $value){ $time1 = explode(':',$value); list($h[$key],$m[$key],$s[$key]) = $time1; $seconds += $s[$key]; $minutes += $m[$key]; $hours += $h[$key]; } $total_sec_min = intval($seconds / 60); $total_seconds = $seconds % 60; #$total_seconds; $total_minutes = $minutes % 60; if($total_sec_min > 0){ $total_minutes = $total_minutes + $total_sec_min; } $total_min_hr = intval($minutes / 60); $total_hours = $hours; if($total_min_hr > 0){ $total_hours = $total_hours + $total_min_hr; } return $total_hours.':'.sprintf("%02s",$total_minutes).':'.sprintf("%02s",$total_seconds); } But I really got hard time when it comes to subtraction. Quote Link to comment https://forums.phpfreaks.com/topic/288782-math-time-subtractions/ Share on other sites More sharing options...
Barand Posted May 26, 2014 Share Posted May 26, 2014 Use DateTime objects $data = array('1:52:37','9:56:39','08:04:22','05:32:20'); echo addTimes($data); //--> 1 days 1 hrs 25 mins 58 secs echo "<br/>"; echo subtractTime('18:33:20','11:40:30'); //--> 0 days 6 hrs 52 mins 50 secs function addTimes ($data) { $dt = new DateTime(); $dt->setTimestamp(0); $dt2 = clone $dt; foreach ($data as $t) { list ($h,$m,$s) = explode(':',$t); $di = new DateInterval("PT{$h}H{$m}M{$s}S"); $dt->add($di); } return $dt->diff($dt2)->format('%d days %h hrs %i mins %s secs'); } function subtractTime($t1, $t2) { $dt1 = new DateTime(); list ($h,$m,$s) = explode(':',$t1); $dt1->setTime($h, $m, $s); $dt2 = new DateTime(); list ($h,$m,$s) = explode(':',$t2); $dt2->setTime($h, $m, $s); return $dt1->diff($dt2)->format('%d days %h hrs %i mins %s secs'); } Quote Link to comment https://forums.phpfreaks.com/topic/288782-math-time-subtractions/#findComment-1480888 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.