ruby get Time in given timezone ruby get Time in given timezone ruby ruby

ruby get Time in given timezone


A simpler, more lightweight solution:

Time.now.getlocal('-08:00')

Well documented here.

Update 2017.02.17: If you've got a timezone and want to turn that into an offset you can use with #getlocal inclusive of DST, here's one way to do it:

require 'tzinfo'timezone_name = 'US/Pacific'timezone = TZInfo::Timezone.get(timezone_name)offset_in_hours = timezone.current_period.utc_total_offset_rational.numeratoroffset = '%+.2d:00' % offset_in_hoursTime.now.getlocal(offset)

If you want to do this for moments other than #now, you should study up on the Ruby Time class, particularly Time#gm and Time#local, and the Ruby TZInfo classes, particularly TZInfo::Timezone.get and TZInfo::Timezone#period_for_local


I'd use the ActiveSupport gem:

require 'active_support/time'my_offset = 3600 * -8  # US Pacific# find the zone with that offsetzone_name = ActiveSupport::TimeZone::MAPPING.keys.find do |name|  ActiveSupport::TimeZone[name].utc_offset == my_offsetendzone = ActiveSupport::TimeZone[zone_name]time_locally = Time.nowtime_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"


For an UTC offset of x hours, the current time can be calculated with the help of ActiveSupport in Rails, as the others said:

utc_offset = -7zone = ActiveSupport::TimeZone[utc_offset].nameTime.zone = zone Time.zone.now

or instead of the two lines

DateTime.now.in_time_zone(zone)

Or, if you do not have Rails, one can also use new_offset to convert a locate DateTime to another time zone

utc_offset = -7local = DateTime.nowlocal.new_offset(Rational(utc_offset,24))