Take the 2-minute tour ×

I basically want to autodetect a user's timezone using Rails. I can use this JS code at the user's browser (http://www.onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/) to send a form with the UTC offset and the fact that the time zone observes DST during summer or not, in the user's time zone.

Once I have that info in the server, I want to select the matching time zone. In Rails, I can get a list of time zones with ActiveSupport::TimeZone.all. Also, I can filter zones by utf offset thanks to the utc_offset method. However, I don't know how to filter the timezones that do/don't observe DST.

E.g. suppose a user lives in Amsterdam. Filtering by UTC offset will return Berlin, Belgrado, Madrid, etc timezones, as well as West Central Africa. All of them, but West Central Africa, would be appropriate timezones for a user in Amsterdam (as they provide the same time/date), but I need to filter West Central Africa, which does not perform DST in summer.

How can I do this in Rails? Also, are any of my assumptions wrong?

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

I thought maybe http://geokit.rubyforge.org/ would be helpful. You could get the coordinates of user location (or city/ country). The only thing you would have to do is guess the time zone based on city/country.

share|improve this answer
In fact, in my case I even have lat&lng for the location, but dismissed that approach. Obtaining the associated time zone for some given lat&lng is not an easy task. Geonames provides a way to obtain the time zone given lat&lng, but provides a different naming scheme than Rails (so again I have to guess time zone through UTC offset, and I don't have info about DST in this case). –  Jose May 23 '10 at 14:28
Update: Geonames provide DST info in the response. However, I have the same problem: how to get Rails' timezone given DST and UTC offset. –  Jose May 23 '10 at 15:09
I solved it, finally! As not all Geonames' timezones are included in Rails, I've mapped the missing ones to the best candidates considering UCT offset and DST. A few of them cannot be resolved, but are really rare cases. You can include this initializer ( pastie.org/975171 ) in your Rails application and enjoy timezone detection given lat & lng. –  Jose May 24 '10 at 20:58
add comment

Your Answer


