本文旨在對官方time包有個全面學習了解。不鉆摳細節,但又有全面了解,重點介紹常用的內容,一些低頻的可能這輩子可能都用不上。主打一個花最少時間辦最大事。
-
Duration對象: 兩個time實例經過的時間,以長度為int64的納秒來計數。
常見的duration, golang沒有預設天或者比天大的duration單位,為了避免跨夏令時轉換問題Nanosecond Duration = 1 //納秒
Microsecond = 1000 * Nanosecond //微秒
Millisecond = 1000 * Microsecond //毫秒
Second = 1000 * Millisecond
Minute = 60 * Second
Hour = 60 * Minute獲取單位間的進制數:
fmt.Print(int64(second/time.Millisecond)) // prints 1000- Duration對象上的常用方法
- ParseDuration(s string) (Duration, error) : 將字符串解析為duration, 類似這種字符串"-1h10m10s6ms7us8ns",最前面可以有-表反向,不加就是正向,-只能加在最前面,比如這個例子-加在-10s就會拋錯
- String() string : 以"72h3m0.5s"格式打印
- Since(t Time) Duration : time.Now().Sub(t)的簡便寫法
- Truncate(m Duration) Duration : 保留m的整數倍duration,其余全舍棄,相當于除m(/m)
- Round(m Duration) Duration: 保留距離m的倍數最近的duration,也就除m后會四舍五入
- Duration對象上的常用方法
-
獲取location常用方法
- time.LoadLocation(name string) (*Location, error): name: 預設的時區名,找不到會拋錯,名字大小寫嚴格敏感
chinaLocation, err := time.LoadLocation(“Asia/Shanghai”)
if err != nil {//邏輯上很有必要檢測下
panic(err)
} - time.FixedZone(name string, offset int) *Location : name打印時時區部分原樣展示這個, offset 對于UTC的偏移量(秒)
chinaLocation := time.FixedZone(“CST”, int(860time.Second))
- time.LoadLocation(name string) (*Location, error): name: 預設的時區名,找不到會拋錯,名字大小寫嚴格敏感
-
字符串解析為時間
- time.Parse(layout, value string) (Time, error): time.Parse(“2006-01-02 15:04:05 MST”, “2025-04-17 15:16:17 CST”)
- layout中月/日/小時/分鐘/秒/年分別由1/2/3(24小時就是15)/4/5/6表示;帶時區固定用MST(美國山區時間)。golang本身有些預設layout,
比如time.DateTime就和上面例子中的一樣但不帶MST
- layout中月/日/小時/分鐘/秒/年分別由1/2/3(24小時就是15)/4/5/6表示;帶時區固定用MST(美國山區時間)。golang本身有些預設layout,
- time.ParseInLocation(layout, value string, loc *Location) (Time, error) :同time.Parse差不多,只是時區由第二個參數指定
- time.Parse(layout, value string) (Time, error): time.Parse(“2006-01-02 15:04:05 MST”, “2025-04-17 15:16:17 CST”)
-
時間戳轉換到時間time對象
- time.Unix(sec int64, nsec int64) Time: time.Unix(1744881455, 0)
-
一種創建時間time對象
- time.Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time: time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
-
time對象的常用方法
- In(loc *Location) Time : 原本time實例復制,但時區設為loc,為了打印日期用的。//比如打印美國的時間 time.Now().In(美國Location對象).Format(“2006-01-02 15:04:05 MST”)
- Format(layout string) string :根據layout格式打印出字符串日期 //time.Now().Format(“2006-01-02 15:04:05 MST”)
- Unix() int64 : 獲取time對象的時間戳
- Sub(u Time) Duration : 與時間u的差值 //
start := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
end := time.Date(2000, 1, 1, 12, 0, 0, 0, time.UTC)
diff := end.Sub(start)
fmt.Printf(“difference = %v; 分鐘=%v\n”, diff, diff.Minutes()) //diff = 12h0m0s; 分鐘=720 - AddDate(years int, months int, days int) Time : 增加/減少日期 // 比如AddDate(-1, 2, 3)
-
Sleep(d Duration): 暫停當前協程至少時間d。d為<=0時,sleep立馬返回