如何计算 ruby​​ 中给定时区与 UTC 的偏移量(以小时为单位)? [英] How do I calculate the offset, in hours, of a given timezone from UTC in ruby?

查看:41
本文介绍了如何计算 ruby​​ 中给定时区与 UTC 的偏移量(以小时为单位)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to calculate the offset, in hours, of a given timezone from UTC in Ruby. This line of code had been working for me, or so I thought:

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

但是,结果是返回给我的是标准偏移量,而不是 DST 偏移量.例如,假设

But, it turns out that was returning to me the Standard Offset, not the DST offset. So for example, assume

self.timezone = "America/New_York"

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

If I run the above line, offset_in_hours = -5, not -4 as it should, given that the date today is April 1, 2012.

如果 Ruby 中的有效字符串 TimeZone 考虑了标准时间和夏令时,谁能告诉我如何从 UTC 计算 offset_in_hours ?

Can anyone advise me how to calculate offset_in_hours from UTC given a valid string TimeZone in Ruby that accounts for both standard time and daylight savings?

谢谢!

更新

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

Here is some output from IRB. Note that New York is 4 hours behind UTC, not 5, because of daylight savings:

>> 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

This suggests that there is a bug in TZInfo or it is not dst-aware

更新 2

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

Per joelparkerhender's comments, the bug in the above code is that I was using utc_offset, not utc_total_offset.

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

Thus, per my original question, the correct line of code is:

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

推荐答案

是的,像这样使用 TZInfo:

Yes, use TZInfo like this:

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

获取当前期间:

current = tz.current_period

要了解夏令时是否启用:

To find out if daylight savings time is active:

current.dst?
#=> true

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

To get the base offset of the timezone from UTC in seconds:

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

要从标准时间获得夏令时偏移量:

To get the daylight savings offset from standard time:

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

从UTC获取总偏移量:

To get the total offset from UTC:

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

与 UTC 的总偏移量等于 utc_offset + std_offset.

The total offset from UTC is equal to utc_offset + std_offset.

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

This is the offset from the local time where daylight savings is in effect, in seconds.

这篇关于如何计算 ruby​​ 中给定时区与 UTC 的偏移量(以小时为单位)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆