2014-01-09 62 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(:名稱)' –

相關問題