PHP Session variable - find time difference

2019-09-05 08:07发布

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!

2条回答
Explosion°爆炸
2楼-- · 2019-09-05 08:14

The DateTime object is your friend.

From the PHP manual, a simple example is as follows:

$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');

You can easily adapt your code to something like this:

if(isset($_SESSION['loginTime']))
{
    $logTime = new \DateTime($_SESSION['loginTime']);
    $currentTime = new \DateTime('now');
    $interval = $logTime->diff($currentTime);
    $duration = $interval->format('%H:%i:%s');
}
echo $duration;

Example output:

15:48:57

查看更多
闹够了就滚
3楼-- · 2019-09-05 08:34

This is not related to DST. It is related to timezones in general. The difference between $logTime and now() is usually small, like minutes in the OP. For date 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 of date() to convert the difference from seconds back into H:i:s format. The proper solution is to use DateTime objects and the diff function to get a DateInterval, as David Wyly suggested.

查看更多
登录 后发表回答