如何从utc offset获取tz标识符字符串

时间:2014-03-15 18:25:56

标签: ruby tzinfo

如何在考虑DST变化的情况下,以秒为单位获取tzinfo格式的时区,即America/Toronto的utc偏移量。{/ p>

例如,DST设置最后在2014年3月9日凌晨2:00更改。见偏差

Varinder $ irb

2.1.0 :001 > Time.local(2014,03,9,1,59) 
 => 2014-03-09 01:59:00 -0500 

2.1.0 :002 > Time.local(2014,03,9,2,00) 
 => 2014-03-09 03:00:00 -0400 
2.1.0 :003 >

2.1.0 :006 > Time.local(2014,03,9,2,00).zone
 => "EDT"  # I need America/Toronto format

对于这两个时间示例计算的tzinfo字符串应该相同,因为只有偏差的差异是由于DST。

2 个答案:

答案 0 :(得分:1)

你必须弄清楚DST问题,但这可能会让你到那里(我在PST ...)

> offset = Time.local(2014,03,9,1,59).utc_offset
=> -28800
> ActiveSupport::TimeZone.all.select{|tz| tz.utc_offset == offset}
=> [#<ActiveSupport::TimeZone:0x007fbcacd075a8 @name="Pacific Time (US & Canada)", @utc_offset=nil, @tzinfo=#<TZInfo::TimezoneProxy: America/Los_Angeles>, @current_period=#<TZInfo::TimezonePeriod: #<TZInfo::TimezoneTransitionInfo: #<TZInfo::TimeOrDateTime: 1394359200>,#<TZInfo::TimezoneOffsetInfo: -28800,3600,PDT>>,#<TZInfo::TimezoneTransitionInfo: #<TZInfo::TimeOrDateTime: 1414918800>,#<TZInfo::TimezoneOffsetInfo: -28800,0,PST>>>>, #<ActiveSupport::TimeZone:0x007fbcacd07530 @name="Tijuana", @utc_offset=nil, @tzinfo=#<TZInfo::TimezoneProxy: America/Tijuana>, @current_period=#<TZInfo::TimezonePeriod: #<TZInfo::TimezoneTransitionInfo: #<TZInfo::TimeOrDateTime: 1394359200>,#<TZInfo::TimezoneOffsetInfo: -28800,3600,PDT>>,#<TZInfo::TimezoneTransitionInfo: #<TZInfo::TimeOrDateTime: 1414918800>,#<TZInfo::TimezoneOffsetInfo: -28800,0,PST>>>>]

答案 1 :(得分:1)

试试这个

zone_abbr = Time.local(2014,03,9,2,00).zone
ActiveSupport::TimeZone.
  all.
  select{|tz| tz.tzinfo.current_period.abbreviation.to_s == zone_abbr}.
  map(&:tzinfo).
  map(&:name)

对于"EDT",此代码返回["America/New_York", "America/Indiana/Indianapolis"]