ruby在给定时区内得到时间

在ruby中,我如何获得给定时区的当前时间? 我知道与UTC的偏移量,并希望获得具有该偏移量的时区中的当前时间。

更简单,更轻量级的解决方案:

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

这里有详细记录 。

更新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类 ,特别是Time#gmTime#local ,以及Ruby TZInfo类 ,特别是TZInfo::Timezone.getTZInfo::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将定位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) 

更简单的方法是简单地将偏移量(以整数forms)传递给ActiveSupport :: TimeZone哈希:

 ActiveSupport::TimeZone[-8] => #, @utc_offset=nil, @current_period=#,#>,#,#>>> 

我尝试了gem install active_support ,它安装了activesupport-3.00,这给了我一个错误:

“您的应用程序中没有安装tzinfo。请将其添加到您的Gemfile并运行bundle install”

tzinfo是ActiveSupport使用的一个gem – 它对我来说有点干净,没有任何外部依赖 – 缺点是看起来它看起来像是UTC,所以如果你想让你的时区看起来正确, gem install activerecord将安装你需要的一切。 我将这个答案包括在内,主要是为遇到同样问题/ googlability的其他人提供参考。

(使用gem install tzinfo )安装gem

 require 'tzinfo' zone = TZInfo::Timezone.get('US/Eastern') puts zone.now 

有许多不同的方法来获取时区,但你可以看到一个列表使用

 TZInfo::Timezone.all 

只需添加或减去适当的秒数:

 >> utc = Time.utc(2009,5,28,10,1)#给出了一段时间
 => 2009年5月28日星期五10:01:00 UTC
 >> bst_offset_in_mins = 60#和另一个时区的偏移量
 => 60
 >> bst = t +(bst_offset_in_mins * 60)#只需以秒为单位添加偏移量
 =>星期四五月二十八日11:01:00 UTC 2009#获取新时区的时间