过去几个小时我一直在阅读这个主题,我想我已经掌握了它,但我想要一些确认.
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.
建议的解决方案
存储
date_default_timezone_set('UTC');
$Date = new DateTime();
获取一个 DateTime 对象,其当前日期和时间为 UTC.$Date->format()
获取要插入 MySQL 中 datetime 类型列的值.date_default_timezone_set('UTC');
$Date = new DateTime();
to get a DateTime object with the current date and time in UTC.$Date->format()
to get the value to insert into the datetime type column in MySQL.显示
$Date = new DateTime($row['time']);
用存储的 UTC 时间实例化一个 DateTime 对象.$Date->setTimezone(new DateTimeZone($userTimezone));
将UTC时间调整为用户的时区.$Date->format();
$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.$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?
这不仅使事情变得更简单,而且还克服了模型的问题.如果我在纽约注册了账户但去澳大利亚旅行,我想查看澳大利亚时区的时间.事实上,使用您使用的 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).
这篇关于在 PHP 中处理在不同时区存储/显示日期的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!