Saturday, January 19, 2008

Time Zones

When developing an application with an audience larger than your local neighbourhood in mind, you have to start thinking where your users are. One major point that comes into play is time. The world works on different time zones, and you must realize and honour that. When your application is based on time, time zones become important.

However, time zones are one of those things you just never want to touch. Why? Because usually it's a bloody mess! There are several factors to consider, like the time on your server and database (are they in local time or UTC?), local times for users using time zones, and daylight savings times. All this bundles together to make one messy problem.

RoR's built-in Date/DateTime/Time/TimeZone classes are poorly equipped to handle... well... anything to do with local times. However, because RoR is so extendable, there are always gems and plugins! In order to get everything working nicely, the problem of time zones requires 1 gem and 3 plugins! Wow! That's a lot, but trust me, it makes things much cleaner!

Firstly, there's the TZInfo gem. This little gem provides daylight savings aware transformations of time. This is useful because not everybody observes daylight savings.

Secondly, there's the TZInfo Timezone plugin. This little baby is where most of the magic occurs. This essentially replaces RoR's built-in TimeZone class. It does wonders.

Thirdly, there's the TzTime plugin. This is another little baby that does wonders. It basically replaces RoR's built-in Time class, and works in unison with TZInfo Timezone.

In short, all you do is set TzTime.zone to the current user's time zone, and then you can use things like TzTime.now, which will return you the current local time of the user. Clean and simple!

For an illustration of this, go to:

http://www.caboo.se/articles/2007/2/23/adding-timezone-to-your-rails-app

There was one modification which I needed to make in order for the example to work. Instead of TZInfo::Timezone, I needed to write TzinfoTimezone.

Good luck with time zones, and hopefully, this will keep your application a little bit cleaner (and minus the hair pulling!)


W

No comments: