The program I am trying to write is simple enough, find the difference between two times: today's, and the time the user logs in which is put in a session variable.
The session variable
$_SESSION['loginTime'];
is set to today's date
$_SESSION['loginTime'] = date('Y-m-d H:i:s');
When the user logs out the duration they have been logged in is found using this code on a separate page:
if(isset($_SESSION['loginTime']))
{
$logTime = $_SESSION['loginTime'];
$duration = strtotime(date('Y-m-d H:i:s')) - strtotime($logTime);
$duration = date('H:i:s', $duration);
}
If I were to log in now (22:15 19/04/2016) and stay logged in for 1min 10 sec it returns 01:01:10. I cannot understand where the extra hour is coming from, all timezones are set the same.
- The minutes and seconds are calculated fine but 1 hour is added for seemingly no reason
Thanks for reading! Any help is greatly appreciated!
The DateTime object is your friend.
From the PHP manual, a simple example is as follows:
You can easily adapt your code to something like this:
Example output:
This is not related to DST. It is related to timezones in general. The difference between
$logTime
andnow()
is usually small, like minutes in the OP. Fordate
that results in a time on January 1st, 1970. But 00:00 GMT is 01:00 in most European mainland cities.The quick fix would be to use
gmdate()
instead ofdate()
to convert the difference from seconds back into H:i:s format. The proper solution is to useDateTime
objects and thediff
function to get aDateInterval
, as David Wyly suggested.