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.
now = Time.now
now.in_time_zone('Eastern Time (US & Canada)')
or
now.in_time_zone('Asia/Manila')
I tried a gem install active_support
, it installed activesupport-3.00, which gave me an error:
"You don't have tzinfo installed in your application. Please add it to your Gemfile and run bundle install"
tzinfo
is a gem that ActiveSupport uses -- it was a little cleaner for my purposes, doesn't have any external dependencies -- the downside is that it appears to leave everything looking like it is UTC, so if you want your timezones to look correct, gem install activerecord
will install everything you need. I'm including this answer mostly for reference for others that run into the same issue / googlability.
(use gem install tzinfo
) to install the gem
require 'tzinfo'
zone = TZInfo::Timezone.get('US/Eastern')
puts zone.now
there are a number of different ways to get the timezones, but you can see a list using
TZInfo::Timezone.all
gem install tzinfo
Then
require 'tzinfo'
tz = TZInfo::Timezone.get('US/Pacific')
Time.now.getlocal(tz.current_period.offset.utc_total_offset)
In your environment/development.rb
config.time_zone = 'Rangoon'
In the source code you want to retrieve the time data
Time.zone.now.strftime('%Y-%m-%d %H:%M:%S')
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.numerator
offset = '%+.2d:00' % offset_in_hours
Time.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
An easier way to do it is to simply pass the offset (in integer form) to the ActiveSupport::TimeZone hash:
ActiveSupport::TimeZone[-8]
=> #<ActiveSupport::TimeZone:0x7f6a955acf10 @name="Pacific Time (US & Canada)", @tzinfo=#<TZInfo::TimezoneProxy: America/Los_Angeles>, @utc_offset=nil, @current_period=#<TZInfo::TimezonePeriod: #<TZInfo::TimezoneTransitionInfo: #<TZInfo::TimeOrDateTime: 1320570000>,#<TZInfo::TimezoneOffsetInfo: -28800,0,PST>>,#<TZInfo::TimezoneTransitionInfo: #<TZInfo::TimeOrDateTime: 1331460000>,#<TZInfo::TimezoneOffsetInfo: -28800,3600,PDT>>>>