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

时间:2012-04-01 05:04:25

标签: ruby timezone

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

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

但是,事实证明这是我的标准偏移,而不是DST偏移。例如,假设

self.timezone = "America/New_York"

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

任何人都可以告诉我如何在Ruby中计算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

1 个答案:

答案 0 :(得分:55)

是的,像这样使用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。

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

相关问题