golang处理时间的包time一次性全面了解

本文旨在对官方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后会四舍五入
  • 获取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.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
    • time.ParseInLocation(layout, value string, loc *Location) (Time, error) :同time.Parse差不多,只是时区由第二个参数指定
  • 时间戳转换到时间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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值