如何计算ruby中UTC的给定时区的偏移量(以小时为单位)?

我需要计算Ruby中UTC的给定时区的偏移量(以小时为单位)。 这行代码一直在为我工作,所以我想:

offset_in_hours = (TZInfo::Timezone.get(self.timezone).current_period.offset.utc_offset).to_f / 3600.0 

但是,事实certificate,它返回给我标准偏移,而不是DST偏移。 例如,假设

 self.timezone = "America/New_York" 

如果我运行上面的行,offset_in_hours = -5,而不是-4应该是,因为今天的日期是2012年4月1日。

任何人都可以告诉我如何计算来自UTC的offset_in_hours,因为Ruby中的有效字符串TimeZone既考虑了标准时间又节省了夏令时?

谢谢!


更新

以下是IRB的一些输出。 请注意,由于夏令时,纽约比UTC晚4小时,而不是5小时:

 >> require 'tzinfo' => false >> timezone = "America/New_York" => "America/New_York" >> offset_in_hours = TZInfo::Timezone.get(timezone).current_period.utc_offset / (60*60) => -5 >> 

这表明TZInfo中存在错误,或者它不是dst-aware


更新2

根据joelparkerhender的评论,上面代码中的错误是我使用的是utc_offset,而不是utc_total_offset。

因此,根据我原来的问题,正确的代码行是:

 offset_in_hours = (TZInfo::Timezone.get(self.timezone).current_period.offset.utc_total_offset).to_f / 3600.0 

是的,像这样使用TZInfo:

 require 'tzinfo' tz = TZInfo::Timezone.get('America/Los_Angeles') 

获取当前期间:

 current = tz.current_period 

要了解夏令时是否有效:

 current.dst? #=> true 

要以UTC为单位从UTC获取时区的基本偏移量:

 current.utc_offset #=> -28800 which is -8 hours; this does NOT include daylight savings 

要从标准时间偏移夏令时:

 current.std_offset #=> 3600 which is 1 hour; this is because right now we're in daylight savings 

要获得UTC的总偏移量:

 current.utc_total_offset #=> -25200 which is -7 hours 

UTC的总偏移量等于utc_offset + std_offset。

这是与夏令时生效的当地时间的偏差,以秒为单位。