Fred Mj Fred Mj - 7 months ago 22
PHP Question

Time Subtract in PHP

I need help to subtract 2 times in PHP.

Example:

$date1 = 02:40;
$date2 = 00:00;

$finaldate = $date1 - $date2;


the correct answer will be 21:20.

Answer

Check it out:

if use $date2 as 24:00

$date1 = new DateTime('02:40');
$date2 = new DateTime('24:00');
$finaldate = $date2->diff($date1);
echo $finaldate->format('%h:%i'); // 21:20

But if use $date2 as 00:00

$date1 = new DateTime('02:40');
$date2 = new DateTime('00:00');
$finaldate = $date2->diff($date1);
echo $finaldate->format('%h:%i'); //02:40