有没有办法为本地时区获取TZInfo样式字符串?

时间:2014-01-09 14:00:21

标签: ruby datetime tzinfo

我需要尝试获取一个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”甚至是所有等效时区字符串的列表?

1 个答案:

答案 0 :(得分: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"]