Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: How do I get created_at to show the time in my current time zone?

Seems that when i create an object, the time is not correct. You can see by the script/console output below. Has anyone encountered anything like this, or have any debugging tips?

 >> Ticket.create(...)
=> #<Ticket id: 7, from_email: "[email protected]", ticket_collaterals: nil, to_email: "[email protected]", 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"
like image 331
Schneems Avatar asked Dec 31 '09 04:12

Schneems


1 Answers

It's the timezone issue. Time.now prints time in your local time zone while the rails is reporting it in UTC. See config/environment.rb, it will have 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

You can set the TimeZone in environment.rb to avoid confusion.

# config/environment.rb
config.time_zone = "Central Time (US & Canada)"
like image 65
Chandra Patni Avatar answered Nov 15 '22 00:11

Chandra Patni