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.
Ruby | Time now() function The now() is an inbuilt method in Ruby returns the current time.
A simpler, more lightweight solution:
Time.now.getlocal('-08:00') Time.now.getlocal(-28800)
Well documented here.
Update 2021.12.23: If you've got a tzdata
timezone name like 'US/Pacific' instead of an offset and you're willing to pull in the tzinfo
gem, you could also do this (with thanks to both @chadoh and @kevin from below):
require 'tzinfo' TZInfo::Timezone.get('US/Pacific').now
Not really the problem as posed, but maybe helpful to folks in the future.
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 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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With