您可以使用period_for_local method。对于这些示例,我使用我居住的时区 (America/Sao_Paulo),其中偏移量在冬季(3 月至 10 月)为 -03:00,在夏季(夏令时)为 -02:00:
# Sao Paulo timezone
zone = TZInfo::Timezone.new('America/Sao_Paulo')
# date in January (Brazilia Summer Time - DST)
d = DateTime.new(2017, 1, 1, 10, 0)
period = zone.period_for_local(d)
puts period.offset.utc_total_offset / 3600.0
# date in July (Brazilia Standard Time - not in DST)
d = DateTime.new(2017, 7, 1, 10, 0)
period = zone.period_for_local(d)
puts period.offset.utc_total_offset / 3600.0
输出是:
-2.0
-3.0
utc_total_offset 方法以秒为单位返回偏移量,所以我除以 3600 得到了以小时为单位的值。
请注意,我还使用了3600.0 来强制结果为浮点数。如果我只使用3600,结果将被四舍五入,像Asia/Kolkata(偏移量为+05:30)这样的时区会给出不正确的结果(5 而不是5.5)。
请注意,您必须注意 DST 更改,因为您可以有间隙或重叠。
在圣保罗时区,夏令时从 2017 年 10 月 15 日开始:在午夜,时钟向前移动到凌晨 1 点(并且偏移量从 -03:00 更改为 -02:00),因此所有当地时间 00:00 到 01 之间: 00 无效。在这种情况下,如果你尝试获取偏移量,它会得到一个PeriodNotFound 错误:
# DST starts at October 15th, clocks shift from midnight to 1 AM
d = DateTime.new(2017, 10, 15, 0, 30)
period = zone.period_for_local(d) # error: TZInfo::PeriodNotFound
当 DST 于 2018 年 2 月 18 日结束时,午夜时钟移回 17 日晚上 11 点(并且偏移量从 -02:00 更改为 -03:00),因此本地时间在晚上 11 点和午夜之间存在两次(在偏移量)。
在这种情况下,你必须指定你想要的(通过设置period_for_local的第二个参数),表明你是否想要DST的偏移量:
# DST ends at February 18th, clocks shift from midnight to 11 PM of 17th
d = DateTime.new(2018, 2, 17, 23, 30)
period = zone.period_for_local(d, true) # get DST offset
puts period.offset.utc_total_offset / 3600.0 # -2.0
period = zone.period_for_local(d, false) # get non-DST offset
puts period.offset.utc_total_offset / 3600.0 # -3.0
如果不指定第二个参数,会得到TZInfo::AmbiguousTime 错误:
# error: TZInfo::AmbiguousTime (local time exists twice due do DST overlap)
period = zone.period_for_local(d)