在ruby中,我如何获得给定时区的当前时间?我知道从UTC的偏移量,并希望获得具有该偏移量的时区中的当前时间。
更简单,更轻量级的解决方案:
Time.now.getlocal('-08:00')
记录良好的here。
更新2017.02.17:如果你有一个时区并希望将其转换为偏移量,你可以使用包含DST的#getlocal,这是一种方法:
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)
如果你想在#now
以外的时刻做这个,你应该研究Ruby Time class,特别是Time#gm
和Time#local
,以及Ruby TZInfo classes,特别是TZInfo::Timezone.get
和TZInfo::Timezone#period_for_local
我会使用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"
对于x小时的UTC偏移量,可以在Rails中的ActiveSupport的帮助下计算当前时间,其他人说:
utc_offset = -7
zone = ActiveSupport::TimeZone[utc_offset].name
Time.zone = zone
Time.zone.now
或者代替两条线
DateTime.now.in_time_zone(zone)
或者,如果你没有Rails,也可以使用new_offset
将locate DateTime转换为另一个时区
utc_offset = -7
local = DateTime.now
local.new_offset(Rational(utc_offset,24))
gem install tzinfo
然后
require 'tzinfo'
tz = TZInfo::Timezone.get('US/Pacific')
Time.now.getlocal(tz.current_period.offset.utc_total_offset)
更简单的方法是简单地将偏移量(以整数形式)传递给ActiveSupport :: TimeZone哈希:
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>>>>
我尝试了gem install active_support
,它安装了activesupport-3.00,这给了我一个错误:
“您的应用程序中没有安装tzinfo。请将其添加到您的Gemfile并运行bundle install”
tzinfo
是ActiveSupport使用的一个宝石 - 它对我来说有点干净,没有任何外部依赖 - 缺点是看起来它看起来像是UTC,所以如果你想让你的时区看起来正确,gem install activerecord
将安装你需要的一切。我将这个答案包括在内,主要是为遇到同样问题/ googlability的其他人提供参考。
(使用gem install tzinfo
)来安装gem
require 'tzinfo'
zone = TZInfo::Timezone.get('US/Eastern')
puts zone.now
有许多不同的方法可以获得时区,但您可以看到使用的列表
TZInfo::Timezone.all
now = Time.now
now.in_time_zone('Eastern Time (US & Canada)')
or
now.in_time_zone('Asia/Manila')
在您的environment / development.rb中
config.time_zone = 'Rangoon'
在源代码中,您要检索时间数据
Time.zone.now.strftime('%Y-%m-%d %H:%M:%S')
只需添加或减去适当的秒数:
>> 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