views:

743

answers:

2

In Ruby/Rails, how do I convert a UTC DateTime to another time zone?

+6  A: 
time.in_time_zone(time_zone)

Example:

zone = ActiveSupport::TimeZone.new("Central Time (US & Canada)")
Time.now.in_time_zone(zone)

or just

Time.now.in_time_zone("Central Time (US & Canada)")

You can find the names of the ActiveSupport time zones by doing:

ActiveSupport::TimeZone.all.map(&:name)
# or for just US
ActiveSupport::TimeZone.us_zones.map(&:name)
mckeed
In irb, when I try Time.now.in_time_zone('CST'), I get the error "undefined method 'in_time_zone'". Are there rails classes that I need in order to get this to work?
Drew Johnson
Which version of Rails are you using? Does it work if you do Time.zone.now.in_time_zone(...)?
mckeed
Thanks so much for the code sample. That cleared it up (along with Fred's comment). I was doing so many things wrong, I can't even begin to explain :-)
Drew Johnson
+1  A: 

Try ActiveSupport's TimeWithZone objects manipulated with TimeZone. ActiveSupport also provides the in_time_zone method for converting a UTC time to a specified TimeZone time zone. mckeed's answer shows the code.

Fred
What's the syntax for importing TimeWithZone into my class? Or do I get it by default with Rails?
Drew Johnson
I believe you get it by default. mckeed has the code you need, but you won't see it in irb. You need to run it in Rails.
Fred
You're right - thanks, Fred - it does come with Rails by default. I was grasping at straws, trying to get it working in irb.
Drew Johnson