What's New in Edge Rails: Easier Timezones

Posted by ryan
at 7:59 PM on Thursday, January 24, 2008

The days of forcing time-zone support into your Rails apps with not one, but two plugins are over. It would appear that Rails now has its own way of dealing with timezones via a custom implementation (though it’s still based on the tzinfo gem).

Here’s the deal. Set the Time.zone variable to the local timezone. All further date manipulations will automatically reflect this local time while being saved to the database in UTC. Here’s what that will look like:

1
2
3
4
5
6
7
8
9
10
# Set the local time zone
Time.zone = "Pacific Time (US & Canada)"

# All times will now reflect the local time
article = Article.find(:first)
article.published_at #=> Wed, 30 Jan 2008 2:21:09 PST -08:00

# Setting new times in UTC will also be reflected in local time
article.published_at = Time.utc(2008, 1, 1, 0)
article.published_at  #=> Mon, 31 Dec 2007 16:00:00 PST -08:00

So how can we use this new timezone support in the real world – as in our Rails apps where you let users define their own timezone? We can do this using a before filter to set Time.zone, much in the same way you’re used to doing:

1
2
3
4
5
6
7
8
9
class ApplicationController < ActionController::Base

  before_filter :set_timezone

  def set_timezone
    # current_user.time_zone #=> 'London'
    Time.zone = current_user.time_zone
  end
end

Now your controller actions and views will automatically have their dates represented in the user’s timezone.

To set a default timezone for your app, do so in environment.rb:

1
2
3
Rails::Initializer.run do |config|
  config.time_zone = "Hawaii"
end

To get the current time in the currently set timezone you can use Time.zone.now:

1
2
# Instead of Time.now
Time.zone.now

At the end of the day you’ve got a timezone solution built into Rails that avoids needless dependencies and establishes a common practice for multi-timezone applications.

This article leave you wanting for more (it won’t offend me)? If so, check out Geoff Buesing’s incredibly detailed and thorough timezone writeup. It looks to be the first of a few tutorials by the guy who actually wrote this functionality.

tags: ruby, rubyonrails

What's New in Edge Rails - In Chinese!

Posted by ryan
at 3:05 PM on Tuesday, January 08, 2008

The virus that is Rails is spreading. Thanks to Yudi, my posts on new features in edge rails have all been translated into Chinese. Surely a good sign for Rails and Ruby.

Thanks to Yudi for doing the unenviable task of wading through my diatribes, I hope your hard work is appropriately rewarded.

tags: ruby, rubyonrails