Rahul
Rahul

Reputation: 47086

Rails: saving record from console with Timezone

I created a new object and saved the same through the console. I noticed that created_at and updated_at columns were in GMT format but when I do a Time.now in my console I get the time in my time zone. How can save my records from the console with my local time?

Upvotes: 0

Views: 664

Answers (1)

Tom Harrison
Tom Harrison

Reputation: 14018

Rahul, Rails correctly goes out of its way to store dates in UTC (like GMT) format. I strongly advise against undoing this.

Rails (and ruby) provides Time.zone, Time.local and other methods that help you display the values in the correct local time. Your local time is determined by the settings of your system, but your local time isn't necessarily the same as that of other people using the system. Once you put this on a web server in the wild, people may be in different time zones. You can tell Rails which time zone to use by default in application.rb in this section

# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
config.time_zone = 'Eastern Time (US & Canada)'

This might work OK for cases where most of your users are in the same timezone, but if you want users to be able to see date/times in their timezone, you'll probably want to store their zone in the User record. There's a time_zone_select helper to make it easy to capture that info.

Upvotes: 2

Related Questions