2014-01-09 27 views
4

我需要尝试获取TZInfo样式字符串a-la'America/New_York',它代表我所在系统的本地时区。我无法弄清楚如何去做。有没有办法为本地时区获取TZInfo样式字符串?

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”,甚至是所有等效时区字符串的列表?

+0

看源为['tzlocal.get_localzone()'](https://github.com/regebro/tzlocal)(它是在Python,但时区信息来的地方都是一样的)。它发现一个zoneinfo时区(例如“America/New_York”),它对应于Unix,Win32上的本地时区。 – jfs

回答

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"] 
+0

此外,您还可以选择美国时区,例如美国/波哥大,美国东部时间,美国/纽约州,美国/印第安纳州/印第安纳波利斯,美洲/利马等]和ActiveSupport :: TimeZone.us_zones .MAP(:tzinfo).MAP(:名称)' –

相关问题