Ruby Time 類別提供強大的日期時間操作功能。本文涵蓋當前時間取得、元件分解、格式化輸出、時間運算、時區處理與 Unix 時間戳轉換。
time1 = Time.new
time2 = Time.now # 同義
# 輸出:Mon Jun 02 12:02:39 -0700 2008
time = Time.new
time.year # 2008
time.month # 6
time.day # 2
time.wday # 1 (0=週日)
time.yday # 154
time.hour # 12
time.min # 3
time.sec # 8
time.usec # 247476
time.zone # "UTC"
Time.local(2008, 7, 8) # 本地時間
Time.local(2008, 7, 8, 9, 10) # 本地時間含時分
Time.utc(2008, 7, 8, 9, 10) # UTC 時間
Time.gm(2008, 7, 8, 9, 10, 11) # GMT 時間
values = time.to_a
# [sec, min, hour, day, month, year, wday, yday, isdst, zone]
Time.utc(*values) # 陣列轉 UTC 時間
time.to_s # "Mon Jun 02 12:35:19 -0700 2008"
time.ctime # "Mon Jun 2 12:35:19 2008"
time.strftime("%Y-%m-%d %H:%M:%S") # "2008-06-02 12:35:19"
now = Time.now
past = now - 10 # 10 秒前
future = now + 10 # 10 秒後
diff = future - now # 10.0 秒
time.zone # "UTC"
time.utc_offset # 0
time.isdst # false
time.utc? # true
time.localtime # 轉本地時區
time.gmtime # 轉回 UTC
time.getlocal # 新物件,本地時區
time.getutc # 新物件,UTC
Time.now.to_i # 秒數
Time.at(秒數) # 轉回 Time
Time.now.to_f # 含微秒