Glenn Gillen

Improved timezones in Rails 2.1

The latest release of rails has made the handling of timezones in rails even easier. No longer do you need to install a couple of plugins, although you still need the tzinfo gem.

With the new baked in support for timezones in rails you can ignore the previous article on how to support timezones in rails 1.2.x. Now all you need to do is set the desired timezone you want to be working in: = "Pacific Time (US & Canada)"

Behind the scenes the date will be saved as UTC, but the appropriate timezone conversion will happen for you whenever you output a date or datetime.

> = "Pacific Time (US & Canada)" 
> @post = Post.find :first
> @post.created_at
=> Fri, 08 Feb 2008 09:00:00 PST -08:00
> @post.created_at = Time.utc 2008, 1, 1
> @post.created_at
=> Mon, 31 Dec 2007 16:00:00 PST -08:00

It also makes it a breeze to display timezones that are customised to your end-users locality with a before filter:

class ApplicationsController < ApplicationController
  before_filter :set_timezone

    def set_timezone = current_user.time_zone || "Pacific Time (US & Canada)" 

Alternatively you can specify a default timezone in your environment.rb: do |config|
  config.time_zone = "Pacific Time (US & Canada)" 

Oh and of course will still return the time according to the server, if you want the current time in the user's local timezone then:

Glenn Gillen

I'm an advisor to, and investor in, early-stage tech startups. Beyond that I'm an incredibly fortunate husband and father. Working on a developer-facing tool or service? Thinking about starting one? Email me and let me know or come to one of our days to help make it a reality.