Golang时间处理

本文主要介绍了Golang时间处理的函数。

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package main

// 解析时间相关

import (
"fmt"
"time"
)

func showTime() {
nowTime := time.Now()
nowYear := nowTime.Year()
nowMonth := nowTime.Month()
nowDay := nowTime.Day()
nowHour := nowTime.Hour()
nowMinute := nowTime.Minute()
nowSecond := nowTime.Second()
fmt.Println(nowTime)
fmt.Println(nowYear)
fmt.Println(nowMonth)
fmt.Println(nowDay)
fmt.Println(nowHour)
fmt.Println(nowMinute)
fmt.Println(nowSecond)
}

func getTimeGap() {
// 获得当地时区时间
nowTime := time.Now()
// 根据相应的格式解析时间
newTime, err := time.Parse("2006-01-02T15:04:05Z07:00", "2021-08-26T12:52:05+08:00") // 如果第二个参数不包含时区信息的话,返回的是UTC时间
if err != nil {
fmt.Println("解析时间错误,错误:", err)
return
}

// 返回时区信息
loc, err := time.LoadLocation("Asia/Shanghai")
fmt.Println("时区信息:", loc)
// 返回时区
nowTimeZone := nowTime.Location()
// 根据相应的格式解析时间
newTime, err = time.ParseInLocation("2006/01/02 15:04:05", "2021/08/26 13:08:00", nowTimeZone)

if err != nil {
fmt.Println("解析时区信息错误,错误:", err)
return
}
timeGap := newTime.Sub(nowTime)
fmt.Println("时间间隔是:", timeGap)
}

func main() {
// showTime()
getTimeGap()
}