4

我需要尝试获取一个 TZInfo 样式字符串 a-la 'America/New_York' 代表我所在系统的本地时区。我不知道该怎么做。

Time.zone

#<ActiveSupport::TimeZone:0x007ff2e4f89240 @name="UTC", @utc_offset=nil, @tzinfo=#<TZInfo::TimezoneProxy: Etc/UTC>, @current_period=#<TZInfo::TimezonePeriod: nil,nil,#<TZInfo::TimezoneOffsetInfo: 0,0,UTC>>>>

这里的 TimezoneProxy#Etc/UTC 字段是我想要的样式,但 UTC 不是本地时间。

Time.now.zone

"EST"

这里的“EST”不是我想要的,我看不到将 Time.now 或 EST 传递给 TZInfo 以获得我想要的方法?

有没有办法根据我当前的时区获取“America/New_York”甚至所有等效时区字符串的列表?

4

1 回答 1

0

您可以尝试使用以下命令查找所有 EST 别名:

current_tz = ActiveSupport::TimeZone['EST']
ActiveSupport::TimeZone.
  all.
  select{|tz| tz.utc_offset == current_tz.utc_offset }.
  map(&:tzinfo).
  map(&:name).
  uniq

会产生

["America/Bogota", "EST", "America/New_York", "America/Indiana/Indianapolis", "America/Lima"]

但我认为这是不正确的,因为夏令时问题。更正确的代码:

current_tz = ActiveSupport::TimeZone['EST']
ActiveSupport::TimeZone.
  all.
  select{|tz| 
    tz.utc_offset == current_tz.utc_offset && 
      tz.tzinfo.current_period.dst? == current_tz.tzinfo.current_period.dst? 
  }.
  map(&:tzinfo).
  map(&:name).
  uniq

会产生

["America/Bogota", "EST", "America/Lima"] 
于 2014-09-11T06:44:03.043 回答