我需要在 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 中的有效字符串 TimeZone 考虑了标准时间和夏令时,谁能告诉我如何从 UTC 计算 offset_in_hours?
谢谢!
更新
这是 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 的基准偏移量:
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。
这是与夏令时生效的本地时间的偏移量,以秒为单位。
关于ruby - 如何计算 ruby 中 UTC 给定时区的偏移量(以小时为单位)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9962038/