譯:Rails之關于時間(時區(qū))

It's About Time (Zones)

這是時間系列的第一篇文章。第二篇的主題是 a case study in multiple time zones。

Ruby提供了兩個類來管理時間:TimeDateTime。Ruby1.9.3之后兩者之間的區(qū)別越來越小。鑒于Time包含閏秒和夏令時的概念。本文中,我們將使用Time來舉例。
TZInfo是一個時區(qū)庫,提供不同時區(qū)的夏令時轉換。它被封裝成了gem并且包含582個不同時區(qū)的數(shù)據(jù)。

Rails中的時區(qū)

Rails中的ActiveSupport::TimeZone封裝了TZInfo,并提供其中146個時區(qū)的數(shù)據(jù)以及更好的時區(qū)格式(例如:用Eastern Time (US & Canada)替換America/New_York)。另外配合 ActiveSupport::TimeWithZone,Rails提供和Ruby中Time類一樣的API,所以TimeActiveSupport::TimeWithZone是可以互換的,你永遠都不需要直接創(chuàng)建一個TimeWithZone實例(new)
執(zhí)行以下命令查看Rails中所有可用的時區(qū):

$ rake time:zones:all
* UTC -11:00 *
American Samoa
International Date Line West
Midway Island
Samoa

* UTC -10:00 *
Hawaii

* UTC -09:00 *
Alaska
...

在console中查看當前時區(qū):

> Time.zone
=> #<ActiveSupport::TimeZone:0x007fbf46947b38
 @current_period=#<TZInfo::TimezonePeriod: nil,nil,#<TZInfo::TimezoneOffset: 0,0,UTC>>>,
 @name="UTC",
 @tzinfo=#<TZInfo::TimezoneProxy: Etc/UTC>,
 @utc_offset=nil>

或臨時設置時區(qū):

# in console
> Time.zone = "Perth"

或在配置文件config/application.rb中永久修改項目時區(qū):

# config/application.rb
config.time_zone = "Perth"

Rails的默認時區(qū)是UTC。最好就保留項目時區(qū)為UTC,讓用戶自己去設置他們各種的時區(qū),下一篇文章a case study in multiple time zones 詳述了這么做的原因。

用戶的時區(qū)

假設每個用戶都擁有自己的時區(qū)。這個可以通過向User表添加time_zone屬性實現(xiàn):

create_table :users do |t|
  t.string :time_zone, default: "UTC"
  ...
end

將時區(qū)保存為字符串形式是因為Rails中大多數(shù)時區(qū)相關方法都接受字符串。因此,應該避免將時區(qū)保存為:enums 格式。
用戶可以設置自己想要的時區(qū)。SimpleForm支持:time_zone,并且提供了一個help方法讓用戶可以在下拉框中選擇時區(qū)。

<%= f.input :time_zone %>

可以在ApplicationController中使用around_action來應用用戶設置的時區(qū)。

# app/controllers/application_controller.rb
around_action :set_time_zone, if: :current_user

private

def set_time_zone(&block)
  Time.use_zone(current_user.time_zone, &block)
end

我們將用戶的時區(qū)信息傳遞給Time.use_zone(ActiveSupport提供的方法)。該方法需要傳遞一個塊,在塊的范圍內設置時區(qū)。所以它只影響一次請求,請求結束之后使用的還是原始時區(qū)(應用默認時區(qū))。
在Rails 3.2.13及更低版本中,需要使用around_filter替代around_action。
最后,在展示時區(qū)時,可以使用in_time_zone方法:

<%= time.in_time_zone(current_user.time_zone) %>

相關API

操作API時最好使用ISO8601標準,該標準用字符串表示日期時間。ISO8601的優(yōu)點是清晰,可讀,廣泛支持并且是按規(guī)則排序的。示例:

> timestamp = Time.now.utc.iso8601
=> "2015-07-04T21:53:23Z"

結尾處的Z代表UTC時間,可以使用以下方法將字符串轉為時間對象:

> Time.iso8601(timestamp)
=> 2015-07-04 21:53:23 UTC

三個時區(qū)

在一個Rails應用中,存在三個不同的時區(qū):

  • 系統(tǒng)時間
  • 應用時間
  • 數(shù)據(jù)庫時間

假設我們將時區(qū)設為Fiji,來看下結果:

# This is the time on my machine, also commonly described as "system time"
> Time.now
=> 2015-07-04 17:53:23 -0400

# Let's set the time zone to be Fiji
> Time.zone = "Fiji"
=> "Fiji"

# But we still get my system time
> Time.now
=> 2015-07-04 17:53:37 -0400

# However, if we use `zone` first, we finally get the current time in Fiji
> Time.zone.now
=> Sun, 05 Jul 2015 09:53:42 FJT +12:00

# We can also use `current` to get the same
> Time.current
=> Sun, 05 Jul 2015 09:54:17 FJT +12:00

# Or even translate the system time to application time with `in_time_zone`
> Time.now.in_time_zone
=> Sun, 05 Jul 2015 09:56:57 FJT +12:00

# Let's do the same with Date (we are still in Fiji time, remember?)
# This again is the date on my machine, system date
> Date.today
=> Sat, 04 Jul 2015

# But going through `zone` again, and we are back to application time
> Time.zone.today
=> Sun, 05 Jul 2015

# And gives us the correct tomorrow according to our application's time zone
> Time.zone.tomorrow
=> Mon, 06 Jul 2015

# Going through Rails' helpers, we get the correct tomorrow as well
> 1.day.from_now
=> Mon, 06 Jul 2015 10:00:56 FJT +12:00

時區(qū)相關查詢

Rails使用UTC時區(qū)將時間戳存入數(shù)據(jù)庫。在數(shù)據(jù)庫查詢中應該始終使用Time.current,Rails會幫我們轉換成正確的時間進行對比。

Post.where("published_at > ?", Time.current)
# SELECT "posts".* FROM "posts" WHERE (published_at > '2015-07-04 17:45:01.452465')

總結

不要使用

* Time.now
* Date.today
* Date.today.to_time
* Time.parse("2015-07-04 17:05:37")
* Time.strptime(string, "%Y-%m-%dT%H:%M:%S%z")

推薦使用

* Time.current
* 2.hours.ago
* Time.zone.today
* Date.current
* 1.day.from_now
* Time.zone.parse("2015-07-04 17:05:37")
* Time.strptime(string, "%Y-%m-%dT%H:%M:%S%z").in_time_zone
  • 始終使用UTC
  • Time.current或者Time.zone.today
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 概念解釋 時區(qū)(Timezone) 為什么會將地球分為不同時區(qū)呢?因為地球總是自西向東自轉,東邊總比西邊先看到太陽...
    黑炭媽閱讀 8,729評論 0 5
  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,695評論 19 139
  • UTC 為協(xié)調世界時。 其中東西十二區(qū)各站7.5度。 UTC 與當?shù)貢r間轉換 在東時區(qū)UTC時間 加上所在時區(qū)時差...
    就叫初九吧閱讀 1,324評論 0 0
  • 1. 概述 在網(wǎng)絡環(huán)境中一般用戶只需要在瀏覽器中輸入url如www.sunny.com就可以到對應服務器獲取相應的...
    ghbsunny閱讀 3,447評論 0 7
  • 我愛上了一場雨 該如何去表達
    留子堯閱讀 733評論 0 2

友情鏈接更多精彩內容