Improved timezones in Rails 2.1

Feb 08, 2008

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:

Time.zone = "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.

> Time.zone = "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

  private
    def set_timezone
      Time.zone = current_user.time_zone || "Pacific Time (US &amp; Canada)" 
    end
end

Alternatively you can specify a default timezone in your environment.rb:

Rails::Initializer.run do |config|
  config.time_zone = "Pacific Time (US &amp; Canada)" 
end

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

Time.zone.now
Hi, I'm Glenn! 👋 I'm currently Director of Product @ HashiCorp, and we're hiring! If you'd like to come and work with me and help make Terraform Cloud even more amazing we have multiple positions opening in Product ManagementDesign, and Engineering & Engineering Management across a range of levels (i.e., junior through to senior). Please send in an application ASAP so we can get in touch.