Jump to content

Math Time Subtractions


Recommended Posts

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_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. 

Link to comment
Share on other sites

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();
    $dt2 = clone $dt;
    foreach ($data as $t) {
        list ($h,$m,$s) = explode(':',$t);
        $di = new DateInterval("PT{$h}H{$m}M{$s}S");
    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');    
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.