Ruby TZInfo和Rails ActiveSupport ::时区UTC_offset差异

时间:2016-07-01 14:54:07

标签: ruby-on-rails ruby datetime

我想找到时区对象的总UTC偏移量。以下是使用TZInfo::TimezoneActiveSupport::TimeZone的两个示例。最终,我想使用ActiveSupport::TimeZone实现,但无法让它给我正确的答案。

#TZInfo implementation
tz = TZInfo::Timezone.get('America/New_York')
tz.current_period.utc_total_offset / 60 / 60
=> -4 (CORRECT)

# Rails implementation
tz = ActiveSupport::TimeZone.new("Eastern Time (US & Canada)")
tz.utc_offset / 60 / 60
=> -5 (WRONG)

为什么ActiveSupport::TimeZone似乎无法考虑dst?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我在ActiveSupport documentation找到了这个。基本上,它正在运行tzinfo.current_period.utc_offset而不是tzinfo.current_period.utc_total_offset

def utc_offset
  if @utc_offset
    @utc_offset
  else
    tzinfo.current_period.utc_offset if tzinfo && tzinfo.current_period
  end
end

所以要完全回答我的问题:我需要以下代码......

tz = ActiveSupport::TimeZone.new("Eastern Time (US & Canada)")
tz.tzinfo.current_period.utc_total_offset / 60 / 60