【问题标题】:Rails: How do I get created_at to show the time in my current time zone?Rails:如何让 created_at 显示当前时区的时间?
【发布时间】:2010-12-31 08:01:27
【问题描述】:

似乎当我创建一个对象时,时间不正确。您可以通过下面的脚本/控制台输出看到。有没有人遇到过这样的事情,或者有任何调试技巧?

 >> Ticket.create(...)
=> #<Ticket id: 7, from_email: "foo@example.com", ticket_collaterals: nil, to_email: "foo2@example.com", body: "hello", subject: "testing", status: nil, whymail_id: nil, created_at: "2009-12-31 04:23:20", updated_at: "2009-12-31 04:23:20", forms_id: nil, body_hash: nil>
>> Ticket.last.created_at.to_s(:long)
=> "December 31, 2009 04:23"
>> Time.now.to_s(:long)
=> "December 30, 2009 22:24"

【问题讨论】:

    标签: ruby-on-rails datetime time


    【解决方案1】:

    这是时区问题。 Time.now 以您的本地时区打印时间,而 rails 以 UTC 报告时间。见config/environment.rb,会有config.time_zone = "UTC"

    >> Ticket.create(...)
    >> Ticket.last.created_at.utc
    => Thu, 31 Dec 2009 04:41:58 UTC +00:00
    >> Time.now.utc
    => Thu Dec 31 04:42:18 UTC 2009
    >> Time.now
    => Wed Dec 30 20:44:50 -0800 2009
    

    您可以在environment.rb 中设置时区以避免混淆。

    # config/environment.rb
    config.time_zone = "Central Time (US & Canada)"
    

    【讨论】:

    • 运行“rake time:zones:all”以获取实际列表。你需要像“中部时间(美国和加拿大)”这样的东西,而不仅仅是“CST”。
    • 只是想从 rails 3.0 中添加,config.time_zone 位于 application.rb 而不是 environment.rb
    • 我设置了 time_zone 配置,但 rails 仍然给我 UTC 时间戳。我错过了什么吗?现在是 Rails 5,所以可能有什么变化?
    猜你喜欢
    • 2012-07-27
    • 2015-04-28
    • 1970-01-01
    • 2012-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    相关资源
    最近更新 更多