尋找一種方法來獲得我自己的時區,我可以將其傳遞給application.rb中的config.time_zone,以便在Rails中進行設置。背景:我允許用戶在yaml配置中指定他們的時區,但是如果沒有設置,我想明確地使用該框的時區。我有有一個值設置,因爲我使用它作爲參考轉換時區顯示 - 每個用戶登錄到Rails應用程序可以設置他們的個人時區,我會爲他們做轉換。如何在ruby中獲得我自己的TimeZone?
然而,似乎是用Ruby或者Rails這樣做沒有很好的API。 Time.now.zone返回3個字母的代碼(例如EDT或CDT),但是由於它不夠詳細,所以不能通過,因爲TZInfo類只接受「long」描述。
這裏是我現在在做什麼,這似乎很哈克:
time_zone = CONFIG[:time_zone] # set your local time zone here. use rake time:zones:local to choose a value, or use UTC.
unless time_zone
# try to detect one
if File.exists?('/etc/localtime')
path = File.readlink('/etc/localtime')
items = path.split("zoneinfo/")
if items.length == 2
time_zone = items[1]
end
end
unless time_zone
puts "*** Warning: no time zone is set in config/config.yaml and could not detect system time. Using UTC as the default time; behavior may be unexpected."
time_zone = "UTC"
end
end
config.time_zone = time_zone
更好的想法的傢伙?
它沒有。它返回一個3字母的代碼,如CDT,例如,可以表示中央夏令時(美國)或中央夏令時(澳大利亞)。所以你不能將它傳遞給config.time_zone,或者將它用作使用TZInfo轉換時區的基礎。 – 2013-04-10 15:04:19
看到我的編輯,讓我知道這是否有助於任何 – Eugene 2013-04-10 15:15:31
它可能是沒有辦法,我可以通過Time.now.gmt_offset + Time.now.zone爲了獲得TimeZone的名字我可以傳遞給config.time_zone的API或TZInfo :: Timezone.get? – 2013-04-10 15:21:26