Jump to content

Math Time Subtractions


lilmer

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

Link to comment
https://forums.phpfreaks.com/topic/288782-math-time-subtractions/
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();
    $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');    
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.