本文旨在对官方time包有个全面学习了解。不钻抠细节,但又有全面了解,重点介绍常用的内容,一些低频的可能这辈子可能都用不上。主打一个花最少时间办最大事。以下是博主肝了半天通读了遍官方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立马返回
官方文档: https://pkg.go.dev/time