一文带你了解Go语言中time包的时间常用操作

前言

在日常开发中,我们避免不了时间的使用,我们可能需要获取当前时间,然后格式化保存,也可能需要在时间类型与字符串类型之间相互转换等。本文将会对 Gotime 包里面的常用函数和方法进行介绍。

Now():获取当前本地的时间

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    fmt.Println(now) // 2022-12-03 21:06:16.1658077 +0800 CST m=+5.936223001
}

Now() 函数返回的是一个 time 包内置的一个结构体 Time

获取具体时间单位的值(yeah、month、day ······)

根据 Now() 的返回的 Time 结构体,我们通过其方法可以获取到具体的时间单位的值,例如 年、月、日等等。

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    fmt.Println("年:", now.Year())
    fmt.Println("月:", now.Month())
    fmt.Println("数字格式的月:", int(now.Month()))
    fmt.Println("日:", now.Day())
    fmt.Println("时:", now.Hour())
    fmt.Println("分:", now.Minute())
    fmt.Println("秒:", now.Second())
}

通过 Time 结构体的 Year()Month()Day()Hour()Minute()Second() 这些方法,可以获取到当前时间的 年、月、日、时、分、秒的值。

时间格式化

通过 Time 结构体的 Format(layout string) 方法可以将时间转换成指定格式并以 string 类型返回。

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    format1 := now.Format("2006-01-02 15:04:05")
    format2 := now.Format("2006/01/02 15:04:05")
    format3 := now.Format("2006-01-02")
    format4 := now.Format("2006/01/02")
    format5 := now.Format("15:04:05")

    fmt.Println(format1) // 2022-12-03 22:27:56
    fmt.Println(format2) // 2022/12/03 22:27:56
    fmt.Println(format3) // 2022-12-03
    fmt.Println(format4) // 2022/12/03
    fmt.Println(format5) // 22:27:56
}

其中 layout 格式参数,Go 强制我们使用 2006-01-02 15:04:05 这个固定的值,连接符如 - 可以改变,但是数字不能变,否则时间会对不上。

获取秒、微秒、毫秒、纳秒

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    // 获取秒
    fmt.Println(now.Unix()) // 1670078476
    // 获取毫秒
    fmt.Println(now.UnixMilli()) // 1670079987508082
    // 获取微秒
    fmt.Println(now.UnixMicro()) // 1670079987508082
    // 获取纳秒
    fmt.Println(now.UnixNano()) // 1670079987508082500
}

通过 time 结构体的 Unix()UnixMilli()UnixMicro()UnixNano() 方法可以获取对应是秒时间戳、毫秒时间戳、微秒时间戳和纳秒时间戳。

通过指定年月日等参数获取时间

import (
    "fmt"
    "time"
)

func main() {
    date := time.Date(2002, 12, 03, 12, 12, 12, 0, time.UTC)
    fmt.Println(date) // 2022-12-03 12:12:12 +0000 UTC
}

通过 Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time 函数,传入指定的年月日等参数,获取指定是时间变量。

时间戳与时间的转换

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()

    time1 := time.Unix(now.Unix(), 0).Format("2006-01-02 15:04:05")
    time2 := time.UnixMilli(now.UnixMilli()).Format("2006-01-02 15:04:05")
    time3 := time.UnixMicro(now.UnixMicro()).Format("2006-01-02 15:04:05")
    fmt.Println(time1) // 2022-12-03 23:03:33
    fmt.Println(time2) // 2022-12-03 23:03:33
    fmt.Println(time3) // 2022-12-03 23:03:33
}

通过 Unix()UnixMilli()、和 UnixMicro() 方法可以将对应时间戳转换成当前时间并格式化。

字符串转时间格式

import (
   "fmt"
   "time"
)

func main() {
   t1, err := time.Parse("2006-01-02 15:04:05", "2022-12-03 13:00:00")
   if err != nil {
      fmt.Println("err: ", err)
      return
   }
   fmt.Println(t1) // 2022-12-03 13:00:00 +0000 UTC

   t2, err := time.Parse("2006-01-02", "2022-12-03")
   if err != nil {
      fmt.Println("err: ", err)
      return
   }
   fmt.Println(t2) // 2022-12-03 00:00:00 +0000 UTC

   t3, err := time.Parse("15:04:05", "13:00:00")
   if err != nil {
      fmt.Println("err: ", err)
      return
   }
   fmt.Println(t3) // 0000-01-01 13:00:00 +0000 UTC
}

通过 Parse(layout, value string) (Time, error) 函数将字符串转成 time 时间。layout 格式必须与 value 的格式相对应,否则会返回 error

时间的添加和减少操作

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    newTime := now.Add(time.Hour * 1)
    fmt.Println(newTime.Format("2006-01-02 15:04:05"))
}
  • 通过 (t Time) Add(d Duration) Time 方法,可以对时间进行添加或减少操作,传入的参数是正数表示添加,负数表示减少。添加单位有天、小时、分钟等。
  • Duration 表示所添加的时间,time.Hour 表示小时单位,除此之外还有 time.Minute 分钟单位、time.Second 秒单位等。

计算两个时间的时间差

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    newTime := now.Add(time.Hour * 1)
    fmt.Println(newTime.Sub(now)) // 1h0m0s
}

通过 Sub(u Time) Duration 方法可以计算两个时间的时间差。

计算当前时间与某个时间的时间差

import (
    "fmt"
    "time"
)

func main() {
    beforeTime := time.Now().Add(time.Hour * -1)
    fmt.Println(time.Since(beforeTime)) // 1h0m0s
}

通过 Add(d Duration) Time 方法将当前时间减少一小时,然后通过 Since(t Time) Duration 函数比较当前时间与其他时间的时间差。

判断当前时间是否在某个时间之前

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    date := time.Date(2022, 12, 03, 12, 12, 12, 0, time.UTC)
    fmt.Println(now.Before(date)) // false
}

通过 Before(u Time) bool #方法,判断当前的时间是否在传入的时间之前,返回值为布尔值,true 为是,false 为否。

判断当前时间是否在某个时间之后

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    date := time.Date(2022, 12, 03, 12, 12, 12, 0, time.UTC)
    fmt.Println(now.After(date)) // true
}

通过 After(u Time) bool 方法,判断当前的时间是否在传入的时间之后,返回值为布尔值,true 为是,false 为否。

小结

本文介绍了如果获取当前时间、在当前时间的前提下获取具体的年月日时分秒、时间格式化和时间戳与时间的转换以及计算时间差的方法等。掌握了这些函数和方法的使用,应对开发中 时间操作的场景不成问题。

原文地址:https://juejin.cn/post/7172949400208015397