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
2010-04-23 02:42:47
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
2010-04-23 02:59:19
Which version of Rails are you using? Does it work if you do Time.zone.now.in_time_zone(...)?
mckeed
2010-04-23 14:49:49
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
2010-04-23 19:20:28
+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
2010-04-23 02:49:13
What's the syntax for importing TimeWithZone into my class? Or do I get it by default with Rails?
Drew Johnson
2010-04-23 03:04:28
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
2010-04-23 04:32:56
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
2010-04-23 19:21:43