Rails Edge Timezones February 9th, 2008

UPDATE: in_current_time_zone was removed and in_time_zone now defaults to the current timezone
When I work on feedish I generally start coding sessions by using piston to make sure I'm on the bleeding edge. Which is dangerous sometimes, but gives me a chance to try out new stuff in a pretty low pressure environment (since feedish has a user base of, um 2 at the moment). I'll open it up for more people eventually, just not quite there yet.

So yesterday I decided to take advantage of being on edge and use the new timezones code, since I had been dreading and putting off doing timezone stuff for a while. Ryan Daigle had a nice write up of the change, but I found I still had a couple questions when I got down to it. So I just wanted to include my notes on switching from the plugins to the built in edge stuff to help ease the transition for others.

First things first, make sure you have the latest tzinfo gem installed:

sudo gem install tzinfo
Now if you have the tzinfo and tzinfo_timezone plugins installed, delete them. Otherwise you get confusing errors.

Now then, you'll probably still want to make sure your database is using UTC, so make sure this is in your environment.rb:
ENV['TZ'] = 'UTC'
While you are in there you'll want to set the default timezone for your application as well:
config.time_zone = "Central Time (US & Canada)"
Now activerecord will be off and running, so any records you load will automagically convert times to the default zone.

Times that don't come from activerecord are not so nice though. You'll need to take care of these yourself. Two things to remember here. How to get now and how to convert regular times to the current time zone, those would be here:
# Time.now converted to current timezone
Time.zone.now
# Convert a time, in this case now, to the current timezone (same result as above)
Time.now.in_time_zone
Finally, to customize the time zone on a per request basis you can add this to your application controller:
# Change to the Hawaii time zone (if only it were that easy to travel there)
Time.zone = "Hawaii"
That should pretty much take care of it, enjoy.

tags: edge