Rails set timezone per request

Sometimes we need to have a request be processed in a particular timezone in Rails. To set a timezone per request in Rails, we can have an around filter that sets timezone, runs the requests and then resets timezone to what it was before the request.

We can set Timezone in Rails with the help of code given below.

Time.zone = 'Asia/Kolkata'

This will set the time zone to Asia/Kolkata.

Problem with setting timezone

The problem with this approach is that it will use the time zone Asia/Kolkata to the next subsequent Rails requests on the same thread.

Please avoid setting timezone in rails to avoid timezone issues in the Rails application.

Set timezone per request

Add an around_filter and set Time.zone.

class ApplicationController
  around_filter :set_time_zone


  def set_time_zone
    old_time_zone = Time.zone
    Time.zone = 'Asia/Kolkata' # current_user.time_zone
    Time.zone = old_time_zone

This performs following things.

  • Store old time zone before setting a timezone for a request.
  • Set a new timezone per request in around_filter.
  • Ensure old time zone is restored when the request processing is completed.