9

In config/application.rb I have "config.time_zone = 'UTC'" (without quotes) in the file. I am assuming this is to make the conversion from the user's time, which is entered into the view, to UTC, which is stored in the database. My question is, how do I convert the UTC value from the database to the user's local time to display in the view? I have read that rails takes care of that automatically - how do I tell it to do this?

I have a timezone field in each user's row in the database, I'm just not sure what to store in there, also. I know about rake time:zones:all - I just don't know how all of this fits together in rails 3!

Thank you,

sk

dingalingchickenwiing
  • 1,937
  • 3
  • 20
  • 30

1 Answers1

17

When working in multi-zone environment it's wise to have time zone set to UTC. That's perfectly valid in your application.rb

Rails will automatically transform all time to the current time zone, that can be set with

Time.zone = "some-zone"

What I use is a before_filter in ApplicationController where I set the time zone according to the current user. Then all operations works within this zone and you don't need to think about it in your controllers/models/views.

Suppose that you have some model Foo with some datetime field. Then working in the irb console:

Time.zone = "Prague"
x = Foo.create(:it_will_happen_at => Time.zone.now)
x.it_will_happen_at # => Sat, 25 Sep 2010 13:45:46 CEST +02:00 

Time.zone = "London"
# it is needed to refresh the field after a time zone has changed.
# In normal situation it'd not be needed, it's just for this console example
x.reload
x.it_will_happen_at # => Sat, 25 Sep 2010 12:44:46 BST +01:00 

When you take a look into the DB, you'll find that value is Sat, 25 Sep 2010 11:45:46 UTC.

As for the zone value I prefer names of cities as it works smoothly with daylight savings (summer / winter time).

Radek Paviensky
  • 8,316
  • 2
  • 30
  • 14