Rails:如何让created_at显示当前时区的时间?

时间:2009-12-31 04:28:45

标签: ruby-on-rails datetime time

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

 >> 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"

1 个答案:

答案 0 :(得分:15)

这是时区问题。 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中设置TimeZone以避免混淆。

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