How to subtract 00:30 from 22:30?

Hello everybody,
I know how to subtract between two time values, but the problem is appeared in some positions.
I use this code:
<?php
$startTime = new DateTime(‘22:00:00’);
$endTime = new DateTime('00:30:00 ');
$duration = $startTime->diff($endTime); //$duration is a DateInterval object
echo $duration->format("%H:%I:%S");
It is good in some positions, but for the mentioned case I expect to show “02:30” instead of “21:30”
How to solve it.
Thanks in advance.

You need to include the dates in your DateTime declarations. The diff in your code is finding the difference between 00:30 today and 22:30 today, which is the answer you’re getting: 21:30.

If you were to get the difference between 22:30 today and 00:30 tomorrow, that would be 02:30:

$startTime = new DateTime('2020-06-05 22:00:00');
$endTime = new DateTime('2020-06-06 00:30:00');
$duration = $startTime->diff($endTime);
echo $duration->format("%H:%I:%S");
// 02:30:00
1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service