views:

471

answers:

2

I am working on a Rails application that needs to handle dates and times in users' time zones. We have recently migrated it to Rails 2.1 and added time zone support, but there are numerous situations in which we use Time#utc and then compare against that time. Wouldn't that be the same as comparing against the original Time object?

When is it appropriate to use Time#utc in Rails 2.1? When is it inappropriate?

A: 

If your application has users in multiple time zones, you should always store your times in UTC (any timezone would work, but you should stick with the most common convention).

Let the user input in local time, but convert to UTC to store (and compare, and manipulate). Then, convert back from UTC to display in each users' local time zone.

Ian Terrell
+6  A: 

Hey There,

If you've set:

config.time_zone = 'UTC'

In your environment.rb (it's there by default), then times will automagically get converted into UTC when ActiveRecord stores them.

Then if you set Time.zone (in a before_filter on application.rb is the usual place) to the user's Time Zone, all the times will be automagically converted into the user's timezone from the utc storage.

Just be careful with Time.now.

Also see:

http://mad.ly/2008/04/09/rails-21-time-zone-support-an-overview/

http://errtheblog.com/posts/49-a-zoned-defense - you can use the JS here to detect zones

Hope that helps.

nikz