✍️ time包在实际中经常用到,可以对比python中的time库进行学习
1. 获取年月日
func timeDemo() {
now := time.Now() //获取当前时间
fmt.Printf("current time:%v\\n", now)
year := now.Year()
month := now.Month()
day := now.Day()
hour := now.Hour()
minute := now.Minute()
second := now.Second()
// 年月日时分秒
fmt.Println(year, month, day, hour, minute, second)
}
out
current time:2022-06-30 17:32:01.9837588 +0800 CST m=+0.003915501
2022 June 30 17 32 1
2. 获取时间戳
func demostampDemo() {
now := time.Now() //获取当前时间
timestamp := now.Unix() //秒级时间戳
milli := now.UnixMilli() //毫秒级时间戳 Go1.17+
micro := now.UnixMicro() //微妙时间戳GO1.17+
nano := now.UnixNano() //纳秒时间戳
fmt.Println(timestamp, milli, micro, nano)
}
out
1656581851 1656581851094 1656581851094900 1656581851094900600
3. 时间戳转时间
func unixDemo() {
ret := time.Unix(1654570899, 0) //前面是s,后面是标志位,一般是0
fmt.Println(ret)
fmt.Println(ret.Year())
fmt.Println(ret.Month())
}
out
2022-06-07 11:01:39 +0800 CST
2022
June
4. 当前时间加减操作
func jiange() {
fmt.Println(time.Second)
//now+1h
now := time.Now()
//当前时间+24h
fmt.Println(now.Add(24 * time.Hour))
//当前时间加10分钟
fmt.Println(now.Add(10 * time.Minute))
//sub
//equal
//before after
}
out
1s
2022-07-05 17:50:36.8357548 +0800 CST m=+86400.004206301
2022-07-04 18:00:36.8357548 +0800 CST m=+600.004206301
5. 时间格式转换
func formatDemo() {
now := time.Now()
fmt.Println(now.Format("2006-01-02"))
fmt.Println(now.Format("2006/01/02 15:04:05"))
fmt.Println(now.Format("2006/01/02 03:04:05 PM")) //没有PM默认就是AM,03表示上午
fmt.Println(now.Format("2006/01/02 03:04:05.000")) //
}
out
2022-07-05
2022/07/05 11:18:38
2022/07/05 11:18:38 AM
2022/07/05 11:18:38.597
6. 解析时间格式
func timestamp() {
timeObj, err := time.Parse("2006-01-02", "2022-06-07") // 给日期,解析成时间对象
if err != nil {
fmt.Printf("parse time failed err:%v\\n", err)
return
}
fmt.Println(timeObj)
fmt.Println(timeObj.Unix())
}
out
2022-06-07 00:00:00 +0000 UTC
1654560000
7. 时间格式化
Unix Time是自1970年1月1日 00:00:00 UTC 至当前时间经过的总秒数。下面的代码片段演示了如何基于时间对象获取到Unix 时间。
time.Format
函数能够将一个时间对象格式化输出为指定布局的文本表示形式,需要注意的是 Go 语言中时间格式化的布局不是常见的Y-m-d H:M:S
,而是使用 2006-01-02 15:04:05.000
(记忆口诀为2006 1 2 3 4 5)。
其中:
- 2006:年(Y)
- 01:月(m)
- 02:日(d)
- 15:时(H)
- 04:分(M)
- 05:秒(S)