# 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');

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.

##### 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

{
\$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");
}
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');
}
```
##### Share on other sites

This thread is more than a year old. Are you sure you have something important to add to it?

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account. ×   Pasted as rich text.   Restore formatting

Only 75 emoji are allowed.