Manage timezone properly in rails

I have a backend written in RoR, and I need to manage many requests from different peers around the world. I have the following questions:

Upvotes: 1

Views: 1307

Answers (2)

Prakash Murthy
Prakash Murthy

Reputation: 13057

Not a good idea to change config.timezone for each request, but yes, timezone should be handled on per request basis.

Check out the excellent & comprehensive blogpost titled Working with time zones in Ruby on Rails by the folks at elabs for advice on how to deal with multiple timezones.

Ryan Bates' revised version of Time Zones RailsCasts episode is another good resource.

Upvotes: 1

Lummo
Lummo

Reputation: 1169

Based on the answers to this question: Convert Time from one time zone to another in Rails

It seems like using config.timezone is a bad idea due to threading issues.

I would recommend using the ActiveSupport TimeZone and TimeWithZone classes. This allows you to do things along the lines of:

# Return the simultaneous time in Time.zone or the specified zone
Time.now.in_time_zone                      # => Tue, 13 Jul 2010 01:20:55 EDT -04:00
Time.now.in_time_zone(Time.zone)           # => Tue, 13 Jul 2010 01:20:55 EDT -04:00
Time.now.in_time_zone("Asia/Vladivostok")  # => Tue, 13 Jul 2010 16:20:55 VLAST +11:00
Time.now.in_time_zone(-3.hours)            # => Tue, 13 Jul 2010 02:20:55 BRT -03:00

# Switch to a given timezone within a block
Time.use_zone "Asia/Vladivostok" do
  Time.zone.now # => Tue, 13 Jul 2010 16:20:55 VLAST +11:00
end

Sample code is from http://ofps.oreilly.com/titles/9780596521424/active-support.html

Take a look under 'Time Zone Conversions'

Upvotes: 5

Related Questions