Ron van der Heijden Ron van der Heijden - 2 months ago 22
PHP Question

Time difference using strtotime

This shouldn't be hard, but still I don't understand what is happening.

<?php
echo date( 'H:i', strtotime( '09:00' ) - strtotime( '08:00' ) );
// returns 02:00 instead of 01:00

echo date( 'H:i', strtotime( '18:45' ) - strtotime( '17:15' ) );
// returns 02:30 instead of 01:30

echo date( 'H:i', strtotime( '17:00' ) - strtotime( '09:00' ) );
// returns 09:00 instead of 08:00


What is adding the extra hour?



So maybe I need to add a date?

<?php
echo date( 'H:i', strtotime( '22-09-2016 17:00:00' ) - strtotime( '22-09-2016 09:00:00' ) );
// still 09:00 instead of 08:00


Some extra information



I am using Laravel en tested in Xampp.

In Laravel /config/app.php
'timezone' => 'Europe/Amsterdam',


In Xampp
date_default_timezone_set('Europe/Amsterdam');


Still no difference.

This calculation is done in the blade template where I cannot access the DateTime class.

I found a way to use the DateTime class. Another solution was changing the timezone to
UTC
, but then all my other timestamps are wrong.

Answer

find difference using DateTime object like

$time1 = new DateTime('18:45');
$time2 = new DateTime('17:15');
$interval = $time1->diff($time2);
echo $interval->format('%H:%I');