在 PHP 中处理在不同时区存储/显示日期的最佳方法?
过去几个小时我一直在阅读这个主题,我想我已经掌握了它,但我想要一些确认.
I've been reading up on this topic for the past few hours, and I think I've got a handle on it, but I'd like some confirmation.
情况
我希望加利福尼亚州的用户能够发布将存储在 MySQL 中的评论.然后,我希望德克萨斯州的用户能够查看评论,并将发布日期调整为他或她的时区.
I want a user in, say, California to be able to post a comment that will be stored in MySQL. I then want a user in, say, Texas to be able to view the comment with the post date adjusted to his or her time zone.
建议的解决方案
存储
- 在应用程序启动时运行以下命令,以便所有日期函数都使用 UTC 时区:
date_default_timezone_set('UTC');
$Date = new DateTime();
获取一个 DateTime 对象,其当前日期和时间为 UTC.- 使用
$Date->format()
获取要插入 MySQL 中 datetime 类型列的值.
- Run the following at the start of the application so that all date functions use UTC timezone:
date_default_timezone_set('UTC');
$Date = new DateTime();
to get a DateTime object with the current date and time in UTC.- Use
$Date->format()
to get the value to insert into the datetime type column in MySQL.
显示
- 从 JavaScript 中获取用户的时区信息并将其存储在 cookie 中.
- 运行 MySQL SELECT 查询以检索日期时间列值.
$Date = new DateTime($row['time']);
用存储的 UTC 时间实例化一个 DateTime 对象.$Date->setTimezone(new DateTimeZone($userTimezone));
将UTC时间调整为用户的时区.- 使用
$Date->format();
显示
- Get the user's timezone information from JavaScript and store it in a cookie.
- Run a MySQL SELECT query to retrieve the datetime column value.
$Date = new DateTime($row['time']);
to instantiate a DateTime object with the stored UTC time.$Date->setTimezone(new DateTimeZone($userTimezone));
to adjust the UTC time to the user's timezone.- Display using
$Date->format();
这就是必须要做的事情的要点吗?我错过了更好的解决方案吗?感谢您的帮助!
Is that the gist of what has to be done? Am I missing a better solution? Thanks for your help!
推荐答案
还可以更简单.既然你用的是JavaScript,那为什么不在客户端也用JavaScript来调整时区呢?
It can be made simpler still. Since you are using JavaScript then why not use JavaScript to adjust the time zone on the client as well?
- 在服务器上以 UTC 格式存储所有时间
- 将它们作为 UTC 提供给客户
- 客户端使用 JavaScript 将时间调整到本地时区
这不仅使事情变得更简单,而且还克服了模型的问题.如果我在纽约注册了账户但去澳大利亚旅行,我想查看澳大利亚时区的时间.事实上,使用您使用的 JavaScript 可以轻松调整设置,使设计更加动态.其次,可以避免存储用户时区的开销.
Not only does this make things simpler but it also overcomes a problem with your model. If I registered my account in New York but travelling to Australia, I want to see the times as per the Australian time zone. In fact, using JavaScript you use can easily adjust the settings, making the design even more dynamic. Second, you can avoid the overhead of storing the user's time zone.
也就是说,如果您希望您的设计降级到非 JavaScript 浏览器,那么您最好采用完全依赖 HTTP cookie 的服务器端方法(而不是依赖 JS 来获取 cookie).
That said, if you want your design to degrade to non-JavaScript browsers then you are better off taking a full server side approach relying on HTTP cookies (as opposed to relying on JS to fetch cookies).
相关文章