【问题标题】:Rails stores datetime in GMT though it is converted to local timeRails 将日期时间存储在 GMT 中,尽管它已转换为本地时间
【发布时间】:2012-05-15 01:03:58
【问题描述】:

我的 MySQL 将日期时间戳存储在 GMT 中,尽管服务器的时间是 EST。在添加到 MySQL 之前,我将我的日期时间转换为本地(服务器的日期时间 EST),但它存储它 GMt 而不是 EST。这里有什么问题?

item.update_attributes({:request_datetime => Time.parse(date+" "+time+" "+timezone).localtime}) # this becomes EST
puts Time.parse(date+" "+time+" "+timezone).localtime.to_s # prints correct time zone, EST.

mysql> SELECT request_datetime,NOW(),TIMESTAMPDIFF(MINUTE,request_datetime,NOW()) FROM items Where item='2542';
+---------------------+---------------------+----------------------------------------------+
| request_datetime    | NOW()               | TIMESTAMPDIFF(MINUTE,request_datetime,NOW()) |
+---------------------+---------------------+----------------------------------------------+
| 2012-05-05 22:30:02 | 2012-05-05 18:30:05 |                                         -239 |
+---------------------+---------------------+----------------------------------------------+
1 row in set (0.00 sec)

mysql>

【问题讨论】:

  • 这样更好 - SELECT request_datetime,UTC_TIMESTAMP(),TIMESTAMPDIFF(MINUTE,request_datetime,UTC_TIMESTAMP()) FROM items Where item='2542';

标签: mysql ruby-on-rails ruby activerecord timezone


【解决方案1】:

Rails 默认以 UTC/GMT 存储所有时间,并在必要时将其转换为本地时间,这使得无论您的服务器如何都能更轻松地获取正确时间,或者允许您根据每个用户确定时间。

【讨论】:

  • 解释如何更改默认行为可能会很有用:)
  • 在 environment.rb 中设置本地时区后,您可以随时在时间对象上调用 tolocal 以获取 est
【解决方案2】:

将关注添加到application.rb 作品

config.time_zone = 'Eastern Time (US & Canada)'
config.active_record.default_timezone = 'Eastern Time (US & Canada)'

【讨论】:

    猜你喜欢
    • 2021-05-02
    • 1970-01-01
    • 2012-07-24
    • 2013-10-29
    • 2016-11-12
    • 2011-08-29
    • 1970-01-01
    相关资源
    最近更新 更多