Bham - 1 year ago 69

PHP Question

What is the best way to calculate the difference in time, when time is greater than 24 hours.

**Example**

`$time1 = '76:00:00';`

$time2 = '30:00:00';

// result should be 46:00:00

echo date('H:i:s', strtotime($time1) - strtotime($time2));

But this could not be done with this because its greater then 24 hours.

Also in a database i've stored a time like this: 33:30:00

How in php could i format it to: 33:30

Answer Source

Use `\DateTime`

and `\DateInterval`

to perform calculations:

```
$date1 = new \DateTime();
$date2 = new \DateTime();
$time1 = new \DateInterval('PT76H');
$time2 = new \DateInterval('PT30H');
$date1->add($time1);
$date2->add($time2);
$diff = $date1->diff($date2);
echo ($diff->days * 24 + $diff->h) . $diff->format(':%I:%S');
```

Explanation:
It's not possible to perform calculations directly on `DateInterval`

s, so you have to create dates as a basis for calculations. Then add two different intervals to current dates, and calculate a difference between them. `diff()`

returns `\DateInterval`

that contains total number of days, that you have to multiply by 24 to get hours, and hours that don't make full days.