In ruby, how can I get current time in a given timezone? I know the offset from UTC, and want to get the current time in the timezone with that offset.
A:
Just add or subtract the appropriate number of seconds:
>> utc = Time.utc(2009,5,28,10,1) # given a utc time => Thu May 28 10:01:00 UTC 2009 >> bst_offset_in_mins = 60 # and an offset to another timezone => 60 >> bst = t + (bst_offset_in_mins * 60) # just add the offset in seconds => Thu May 28 11:01:00 UTC 2009 # to get the time in the new timezone
stephenr
2010-05-28 09:06:40
+1
A:
I'd use ActiveSupport:
require 'active_support' # needs rubygems
my_offset = 3600 * -8 # US Pacific
# find the zone with that offset
zone_name = ActiveSupport::TimeZone::MAPPING.keys.find do |name|
ActiveSupport::TimeZone[name].utc_offset == my_offset
end
zone = ActiveSupport::TimeZone[zone_name]
time_locally = Time.now
time_in_zone = zone.at(time_locally)
p time_locally.rfc822 # => "Fri, 28 May 2010 09:51:10 -0400"
p time_in_zone.rfc822 # => "Fri, 28 May 2010 06:51:10 -0700"
glenn jackman
2010-05-28 13:52:06