Time包的使用

获取当前时间

1
2
3
4
5
6
7
8
9
10
11
12
func main() {
// 当前时间
now := time.Now()
// 打印年月日 时分秒
fmt.Println(now) // 2021-07-19 21:56:53.340103 +0800 CST m=+0.000077835
fmt.Println(now.Year()) // 年
fmt.Println(now.Month()) // 月
fmt.Println(now.Day()) // 日
fmt.Println(now.Hour()) // 时
fmt.Println(now.Minute()) // 分
fmt.Println(now.Second()) // 秒
}

时间和时间戳操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
func main() {
// 时间
now := time.Now()
// 获取当前unix时间戳
fmt.Println(now.Unix()) // 1626702555
fmt.Println(now.UnixNano()) // 微秒 1626702571601312000

// 将unix时间戳转换成时间
// 获取当前时间戳
ts := time.Now().Unix()

// 将时间戳转换成时间
formatTimeStr := time.Unix(ts,0).Format("2006-01-02 03:04:05")
fmt.Println(formatTimeStr)

// 将时间转换成时间戳
loc,_:= time.LoadLocation("Asia/Shanghai")
tt,_ := time.ParseInLocation("2006-01-02 15:04:05","2021-07-19 22:00:00",loc)
fmt.Println(tt.Unix())

// 将字符串转换成时间戳
tm2,_:= time.Parse("2006/01/02 15:04:05","2021/07/19 22:00:01")
fmt.Println(tm2.Unix())

// unixTime
startTime := time.Unix(0, 0)
fmt.Println(startTime.Format("2006-02-02 15:04:05"))

// 将字符串转时间格式
cTime, err := time.Parse("2006-01-02", "2001-12-01")
fmt.Println(cTime.Format("2006-01-02 15:04:05"), err)
}

时间的加减

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main 

import
"time"
"fmt"


func main() {
t := time.Now() // 获取当前时间
m := t.Format("2006-01-02 15:04:05") //获取当前格式的日期
beforeDay := t.AddDate(0,0,-1) // 三个参数分别是年月日,此处获取的是前一天的日期
beforeMonth := t.AddDate(0,-1,0) // 前一个月的日期
beforeYear := t.AddDate(-1,0,0) // 去年的当天日期
fmt.Println(beforeDay,beforeMonth,beforYear,m)
fmt.Println(beforeDay.Format("2006-01-02 15:04:05"))
}