Rss Feed Tweeter button Facebook button Technorati button Reddit button Linkedin button Webonews button Delicious button Digg button Flickr button Stumbleupon button Newsvine button

A Waage Blog

Ruby, Rails, Life

Archive for the ‘tzinfo’ tag

Converting Timezones in Ruby: TZInfo

with one comment

In a recent Rails project, I was trying to figure out how to allow users to view any email’s “Date:” header in his/her own timezone. Here’s a short explanation about how I accomplished this using Ruby’s TZInfo gem!

Purpose:
If an email was sent out from New York, the header would contain a Date string like the following (notice the offset):

Fri, 24 Oct 2008 18:35:07 -0400 (EST)

Now, it makes sense for a user in Los Angeles to be able to view the Date/time as 15:35 pm, while a user in New York City should be able to view it as 18:35pm.

Here’s what I did.

Of course, I installed TZinfo first:

%>sudo gem install tzinfo

Each user should have a timezone associated. Try the following method for a list of timezones in US:

 >>TZInfo::Country.get('US').zone_identifiers

Let’s take two users as an example. We have lakersfan is on the west coast, and knicksfan is on the east coast:

>> lakersfan.timezone = TZInfo::Timezone.get('America/Los_Angeles')
>> knicksfan.timezone = TZInfo::Timezone.get('America/New_York')

Given a date/time string like the following (could be taken from the email header or elsewhere):

>>timestring = "Fri, 24 Oct 2008 18:35:07 -0400 (EST)"

first call Time.parse(timestring) which will create a time object with offset info. **Note that this is different from calling timestring.to_time (which will disregard offset info and store the Time object as UTC).

>> timestring = "Fri, 24 Oct 2008 18:35:07 -0400 (EST)"
>> Time.parse(timestring)
=> Fri Oct 24 18:35:07 -0400 2008 #Stores the Time object with offset
>> timestring.to_time
=> Fri Oct 24 18:35:07 UTC 2008 #Incorrect - the offset is ignored

Now, once you’ve got the Time object in proper format (with offset), you can just call the ‘utc’ method to convert the time into UTC format:

>> utctime = Time.parse(timestring).utc

Lastly, once the time is in UTC format, you can use any user’s timezone object to call ‘utc_to_local’ method and convert that utc time into the user’s timezone!

>> lakersfan.tz.utc_to_local(utctime)
=> Fri Oct 24 15:35:07 UTC 2008
>> knicksfan.tz.utc_to_local(utctime)
=> Fri Oct 24 18:35:07 UTC 2008

Voila! Lakers fan (west coast) sees the time as 15:35, while the Knicks fan (on east coast) sees the time as 18:35 – the same as the email header.

Written by Andrew Waage

October 25th, 2008 at 6:14 pm

Posted in Ruby and Rails

Tagged with , , ,