How to Set a Time Zone for Each Request in Rails

The Railscast on Time Zones has some sample code that lets you set a thread-local, per-request time zone with a before_filter:

# controllers/application.rb
  before_filter :set_user_time_zone


  def set_user_time_zone = current_user.time_zone if logged_in?

Problem is, the current user’s time zone will leak across to the next request on the same thread. If the next one is by a logged-out user, all times displayed on that next request will show in the first user’s time zone.

To prevent this, use an around_filter:

  around_filter :set_time_zone


  def set_time_zone
    old_time_zone = = current_user.time_zone if logged_in?
  ensure = old_time_zone

You might be tempted to combine the first two lines of set_time_zone into one line with the comma assignment syntax and add “if logged_in?” to the one line in the ensure clause. Don’t do it. If you did that, the user’s time zone would leak out to the next request when the user logs out.

I’ve submitted a Rails patch to use this method in the sample code for the docs.

4 thoughts on “How to Set a Time Zone for Each Request in Rails”

  1. Hi Brian, I’ve been trying to set directly as in:’CST’, I still get UTC if i check is in CDT and is CDT. I’ve also tried, yet still yields UTC. Not sure what to make of all this. My goal is to set the local timezone so I can correctly test a controller action which converts a stored UTC date into a displayable local time – otherwise my test only passes in one timezone!

    1. Hi Revision42,

      ‘CST’ is not one of the names Rails uses for time zones. You can see the full list by looking in the activesupport gem in lib/active_support/values/time_zone.rb.

      The Rails name for CST is “Central Time (US & Canada)”.

      One easy way to see this file is:
      $ gem install gemedit
      $ gem edit activesupport

      This opens activesupport in your editor (whatever EDITOR is set to). Then navigate to the file.

  2. Hi Brian, thanks for the response, it turns out is just a string representation of a time-zone. Whereas ActiveSupport::TimeZone is really what I want to set

    Your code worked for me if I put it directly in the action where it was needed. However the around_filter didnt work for me, the seems to fall out of scope in the yield which surprised me.

Leave a Reply

Your email address will not be published. Required fields are marked *

Feel free to use <a>, <b>, <i>, <strong>, <em>, <strike>, <code>.

Code blocks:
[code language="ruby/javascript/html/css/sass/bash"]