1.获取当前时间
备注
t := time.Now() //获取当前时间,类型是go的时间类型Time
tY := time.Now().Year()
tMo := time.Now().Month()
tD := time.Now().Day()
tH := time.Now().Hour()
tMi := time.Now().Minute()
tS := time.Now().Second()
tNaS := time.Now().Nanosecond()
curTimeDate := time.Date(tY, tMo, tD, tH, tMi, tS, tNaS, time.Local)
fmt.Println("time.Now() = ", t)
fmt.Println("tY:tMo:tD:tH:tMi:tS = ", tY, tMo, tD, tH, tMi, tS)
fmt.Println("curTimeDate = ", curTimeDate)
输出格式如下
time.Now() = 2022-09-08 10:22:19.0001454 +0800 CST m=+0.007427901
tY:tMo:tD:tH:tMi:tS = 2022 September 8 10 22 19
curTimeDate = 2022-09-08 10:22:19.0266219 +0800 CST
说明:从打印结果可以看出,time.Now()和Date()方法都可以获取当前时间,time.Now()用起来比较简单,但是Date()可以获取不同的精确值,如time.Date(tY, tMo, tD, tH, tMi, tS, 0, time.Local)将毫秒省略,精确到秒,结果为:curTimeDate = 2022-09-08 10:25:59 +0800 CST
2、获取当前时间戳
tU := time.Now().Unix() //单位s,打印结果:1662605179
tUNa := time.Now().UnixNano() //单位纳秒,打印结果:1662605179395326000
fmt.Println("tu = ", tU)
fmt.Println("tUNa = ", tUNa)
输出格式如下
tu = 1662605179
tUNa = 1662605179395326000
3.获取当前时间的字符串格式
tStr := time.Now().Format("2006-01-02 15:04:05") //当前时间的字符串,2006-01-02 15:04:05据说是golang的诞生时间,固定写法
fmt.Println("tStr = ", tStr) //打印结果:2022-09-08 10:58:38
4.它们之间的相互转化
- 时间戳 转 时间字符串 (int64 -> string)
tU := time.Now().Unix() //已知的时间戳
tFStr := time.Unix(tU, 0).Format("2006-01-02 15:04:05")
fmt.Println("tFStr = ", tFStr) //打印结果:tFStr = 2022-09-08 11:02:39
- 时间字符串 转 时间 (string -> Time)
tFStr := "2022-09-08 11:02:39"
fT, err := time.Parse("2006-01-02 15:04:05", tFStr)
if err == nil {
fmt.Println("fT = ", fT) //打印结果:2022-09-08 11:02:39 +0000 UTC
}
- 时间字符串 转 时间戳 (string -> int64)
只需要对上面的时间,进行Unix转化即可