【问题标题】:How to handle differences between server time and users local time?如何处理服务器时间和用户本地时间的差异?
【发布时间】:2012-11-30 10:13:49
【问题描述】:

我正在开发针对其他国家/地区的网络应用程序。

现在,为了说明我的想法,我在想这样的事情:

// Illustrates the current time on my server
$time = new DateTime();
echo $time->format("Y-m-d H:i:s P");

// Illustrates the current time for the time the user told my app he is in
$time = new DateTime(null, new DateTimeZone('Europe/London'));
echo $time->format("Y-m-d H:i:s P");

这个的输出是:

2012-11-30 11:02:40 +01:00 // My server time
2012-11-30 10:02:40 +00:00 // The users time

一切都很好,因为我现在可以为用户呈现当前时间。但我需要的是获取用户输入并将其转换为我的服务器时间 - 或者至少我认为这是正确的方法。

用例
伦敦的用户告诉我的应用程序他需要在2012-12-01 19:00:00 执行操作。通过在我的数据库中更新此时间戳,我的 cronjob 将在指定时间执行此操作。但我的用户会在 2012-12-01 18:00:00 上体验到这种情况。

在考虑解决此问题的方法时,我正在处理一些偏移时间,这给了我很多意大利面条代码和一些混乱的数据库表设计。

我如何做到这一点才有意义?

【问题讨论】:

    标签: php codeigniter datetime


    【解决方案1】:

    您可以将DateTime 对象的时区更改为所需的。如果您有用户从他们的时区指定的日期时间,您可以轻松地进行转换。

     $time = new DateTime(null, new DateTimeZone('Europe/London'));
     echo $time->format("Y-m-d H:i:s P");
    
     $time->setTimezone(new DateTimeZone('America/Chicago'));
     echo $time->format("Y-m-d H:i:s P");
    

    【讨论】:

    • 真棒 - 简单而有效。谢谢。
    猜你喜欢
    • 2014-04-18
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-12
    • 1970-01-01
    • 2016-05-12
    • 1970-01-01
    相关资源
    最近更新 更多