PHP Session变量-查找时差 [英] PHP Session variable - find time difference

查看:54
本文介绍了PHP Session变量-查找时差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要编写的程序非常简单,发现两次之间的区别:今天和用户登录的时间都放在会话变量中.

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.

会话变量

$_SESSION['loginTime'];

设置为今天的日期

$_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);

}

如果我现在要登录(2016年4月19日22:15)并保持登录状态1分钟10秒,它将返回 01:01:10 .我不明白多余的时间是从哪里来的,所有时区都设置​​为相同.

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.

  • 分钟和秒计算得很好,但似乎没有理由添加了1小时

感谢您的阅读!任何帮助,我们将不胜感激!

Thanks for reading! Any help is greatly appreciated!

推荐答案

DateTime对象是您的朋友.

The DateTime object is your friend.

PHP手册中,一个简单的示例如下:

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

15:48:57

这篇关于PHP Session变量-查找时差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆