View The Space is Hiring

Tuesday, March 12, 2013

Setting the Rails Timezone to the User's Browser Timezone

Timezones confuse me.

At VTS we have lots of reports and charts that group data by the day. These reports should look different based on the user's configured timezone. I did not want to force all of our users to configure their timezone within our app when they already configured it within their operating system and hence their browser. The only problem... the browser does not pass the timezone to the server by default. You have to take care of it yourself.

The solution is pretty straight forward:
  1. Set each users timezone as a cookie
  2. Each request sets the Rails timezone to the value of that cookie

The above coffee script code uses jsTimezoneDetect to set the browsers timezone within a cookie that will live for the next 365 days. All that is left is setting the timezone during each request.

The above code would go into your ApplicationController. Simple around filter for each request that sets the timezone if it's present. Notice that it sets the back to the original default timezone after each request and, yes, the method is actually thread safe.

Slight Caveat

The timezone is set after each page request on document ready. That means the very first request will not have the cookie set for the server side around_filter and will not set the timezone. I have seen some people out there getting fancy with ajax redirects but this is probably a bit overkill for most use cases.  I start to have nightmares involving infinite redirects.

Since I extracted all of the above into a Rails Engine, you can ignore all of my rambling and just install the browser-timezone-rails gem.

1 comment:

  1. jstimezone is quite buggy and unmaintained... see