我正在开发面向其他国家/地区的 Web 应用程序。
现在,为了说明我的想法,我在想这样的事情:
// 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
。
在考虑解决此问题的方法时,我工作了一些偏移时间,这给我带来了很多意大利面条式代码和一些困惑的数据库表设计。
我怎样才能做到这一点,让它有意义?
最佳答案
您可以将 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");
关于php - 如何处理服务器时间和用户本地时间之间的差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13643106/