我需要计算Ruby中UTC的给定时区的偏移量(以小时为单位).这行代码一直在为我工作,或者我想:
offset_in_hours = (TZInfo::Timezone.get(self.timezone).current_period.offset.utc_offset).to_f / 3600.0
Run Code Online (Sandbox Code Playgroud)
但是,事实证明这是我的标准偏移,而不是DST偏移.例如,假设
self.timezone = "America/New_York"
Run Code Online (Sandbox Code Playgroud)
如果我运行上面的行,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
>>
Run Code Online (Sandbox Code Playgroud)
这表明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
Run Code Online (Sandbox Code Playgroud)
joe*_*son 55
是的,像这样使用TZInfo:
require 'tzinfo'
tz = TZInfo::Timezone.get('America/Los_Angeles')
Run Code Online (Sandbox Code Playgroud)
获取当前期间:
current = tz.current_period
Run Code Online (Sandbox Code Playgroud)
要了解夏令时是否有效:
current.dst?
#=> true
Run Code Online (Sandbox Code Playgroud)
要以UTC为单位从UTC获取时区的基本偏移量:
current.utc_offset
#=> -28800 which is -8 hours; this does NOT include daylight savings
Run Code Online (Sandbox Code Playgroud)
要从标准时间偏移夏令时:
current.std_offset
#=> 3600 which is 1 hour; this is because right now we're in daylight savings
Run Code Online (Sandbox Code Playgroud)
要获得UTC的总偏移量:
current.utc_total_offset
#=> -25200 which is -7 hours
Run Code Online (Sandbox Code Playgroud)
UTC的总偏移量等于utc_offset + std_offset.
这是与夏令时生效的当地时间的偏差,以秒为单位.