Rails 2.1 Timezone Support

I understand the basics of timezone support:

Essentially, I just have to do this:

# controllers/application.rb before_filter :set_time_zone

def set_time_zone   Time.zone = @current_user.time_zone if @current_user end

That will set the timezone to the particular user's stored timezone and all will be well in the world.

The part I am trying to figure out is how to "guess" the user's timezone in the first place. The application I am working on calls for the user registration to be dead simple and not include a huge timezone selection box.

I can think of two methods for guessing timezone:

1) Based on IP Address of client 2) Based on a cookie stored on their computer with their current offset

I would probably go with #2 (i.e store a cookie with their current offset from utc and then use that to fetch the first timezone which matches the offset)

Yes this would be inaccurate in that the wrong timezone may be selected but I would always have a select box in their settings area that would allow them to correct it and it would "get the job done".

Thoughts? Is there a better way?

You can determine the timezone using javascript (as an integer):

var visitortime = new Date();

visitortime.getTimezoneOffset()/60;

You can then set this value either in a cookie or in a hidden form field, depending on whether you would like to reverify the timezone on every page or just when registering.

You’ll have to map this number to an appropriate timezone (make an educated guess). Do know that javascript will give you the opposite of what you will expect:

Brussels for example will give -2 as a result while it is GMT+2.

Best regards

Peter De Berdt