Ruby Snippets

Ruby Unix 時間戳程式碼片段

Ruby 範例,用於取得 Unix 秒、推導毫秒、將時間戳轉換為 Time 物件、格式化 UTC 輸出,以及解析日期字串。

Current Unix timestamp (seconds)
Time.now.to_i
Current Unix timestamp (milliseconds)
(Time.now.to_f * 1000).round
Time from Unix timestamp
Time.at(1700000000)
Time in specific timezone
require "time"
Time.at(1700000000).utc.strftime("%Y-%m-%d %H:%M:%S")

# With tzinfo gem:
require "tzinfo"
tz = TZInfo::Timezone.get("America/New_York")
tz.utc_to_local(Time.at(1700000000).utc)
Formatted string
Time.at(1700000000).strftime("%Y-%m-%d %H:%M:%S")
Timestamp from Time
require "time"
Time.parse("2023-11-15T06:13:20Z").to_i

Ruby 時間戳記基礎

Ruby 的 Time.now.to_i 返回 Unix 秒。當你需要秒的小數,或想為期望 JavaScript 風格時間戳記的 API 計算毫秒時,使用 Time.now.to_f。

轉換並格式化 Ruby 的 Time

用 Time.at(timestamp) 從 Unix 秒建立一個 Time 物件。當你需要不依賴機器本地時區的穩定輸出時,在格式化之前呼叫 utc。

Ruby 生產注意事項

Ruby 的 Time 方法很簡潔,但時區預設值在筆電、伺服器和背景 worker 之間可能不同。把持久化的時間戳記保持為 Unix 秒或 UTC 字串,然後在表現層套用應用程式時區。解析使用者輸入時,包含偏移或時區,以免錯誤地猜測夏令時規則。

  • Unix 秒用 Time.now.to_i
  • 毫秒值用 (Time.now.to_f * 1000).round
  • 穩定的 UTC 輸出用 Time.at(seconds).utc
  • Time.parse 僅用於包含時區或偏移的字串

FAQ

Time.now.to_i 回傳毫秒嗎?
不。Time.now.to_i 回傳整數 Unix 秒。如果你需要秒的小數部分或想得到毫秒,請使用 Time.now.to_f。
為什麼在格式化前呼叫 utc?
utc 使輸出與機器的本地時區無關。這對日誌、API 負載和測試預期很有幫助。
如何驗證 Ruby 時間戳記?
使用 Time.at(seconds).utc.iso8601,並在把值寫入任務、API 或資料庫之前,把結果與期望的 UTC 時刻比較。