Redline Software Inc. - Winnipeg's Leader in Ruby on Rails Development

Rails TimeZone's

I’ve just added TimeZone support to our Redzone Leagues application and have read a few blog posts about setting up TimeZone’s in rails. One popular article on the subject is found here.

One issue that I came across while I was adding TimeZone support to our app, is that I have time fields in many places in the database that have been created with the local time zone, not UTC, which most articles on the subject seem to assume are already in the database. All of the timestamp fields in my database have no time zone support, which the rails migrations create by default (at least using Postgresql, not sure about MySql, etc.)

The common pattern you’ll see in the articles is similar to this…


This assumes the time passed in is already in UTC format, but mine aren’t, they’re in central time.

My solution is to convert the local time to UTC first and then go with the normal conversion used above.


So the time from the database is first converted from the local time to UTC (with the local_to_utc call) and then to the time zone associated with the user (with the utc_to_local call).

I added a default method to the TimeZone class that represents the default time zone used in the app.

class TimeZone
  def self.default
    self["Central Time (US & Canada)"]

Now I can leave my database timestamps as is and still achieve the proper conversions for each user.