1. 在請(qǐng)求的時(shí)候開(kāi)始的時(shí)候重置 TimeZone
#ApplicationController
around_action:set_time_zone
def set_time_zone
old_time_zone = Time.zone
Time.zone = current_user.timezone if user_signed_in?
Stripe.api_key = Setting.value('stripe_api_secret_key')
begin
yield
ensure
Time.zone = old_time_zone
end
end
2. 調(diào)用
要定義一個(gè) DATE_FOMATE, 默認(rèn)的 to_s(:db)
調(diào)用的是UTC 的時(shí)間摧找,并不會(huì)根據(jù)時(shí)區(qū)發(fā)生變化
#initiallizers/time_format.rb
Time::DATE_FORMATS.merge!(
:localdb => '%Y-%m-%d %H:%M:%S'
}
)
#調(diào)用
current_user.created_at.to_s(:localdb)
3. 涉及夏令時(shí)的處理
翻譯叫 daylight savings time
, 指美國(guó)等地區(qū)在夏季天亮的早的時(shí)候偿曙,撥快一個(gè)鐘耻姥,冬天的時(shí)候再撥回來(lái)畔裕,rails 已經(jīng)處理了這個(gè)問(wèn)題耙箍,在存數(shù)據(jù)庫(kù)的時(shí)候就已經(jīng)轉(zhuǎn)換好了孽查,這里列舉幾個(gè)可能用到的方法
#新建 timezone
new_zone = ActiveSupport.new('Alaska')
#用 Alaska 的 zone 解析時(shí)間
time = new_zone.parse("2000-1-1")
#=> Sat, 01 Jan 2000 00:00:00 AKST -09:00
new_zone.now
#=> Fri, 30 Sep 2016 20:25:15 AKDT -08:00
#判斷是否是夏令時(shí), Rails 提供的方法
new_zone.parse("2000-1-1").dst?
#某個(gè)時(shí)間的所處的時(shí)令的開(kāi)始和結(jié)束
tz = ActiveSupport::TimeZone[timezone].tzinfo.period_for_utc(time)
tz.local_end
#=> Sun, 02 Apr 2000 02:00:00 +0000
tz.local_start
#=> Sun, 31 Oct 1999 01:00:00 +0000
#轉(zhuǎn)換時(shí)區(qū)
Time.now.in_time_zone('Alaska')