工夫转换
timeLayout := "2006-01-02 15:04:05"
1. 获取服务器工夫
fmt.Println(time.Now().Format(timeLayout))
2. 获取 UTC 工夫
fmt.Println(time.Now().UTC().Format(timeLayout))
3. 服务器工夫转换为 UTC 工夫
timeStr := "2021-05-18 12:00:00" // 认为服务器工夫
location, _ := time.LoadLocation("Local") // timeStr 是北京工夫,留神应用 Local
localTime, _ := time.ParseInLocation(timeLayout, timeStr, location)
fmt.Println(localTime.UTC().Format(timeLayout)) // 转为 UTC 工夫
````
阐明:留神 timeStr 值,此时咱们把它当做服务器工夫,所以 time.LoadLocation("Local") 应用 Local
### 4.UTC 工夫转换为服务器工夫
timeStr := “2021-05-18 12:00:00” // 认为是 UTC 器工夫
location, _ := time.LoadLocation(“UTC”) // timeStr 是北京工夫,留神应用 UTC
localTime, _ := time.ParseInLocation(timeLayout, timeStr, location)
fmt.Println(localTime.Local().Format(timeLayout)) // 转为 Local 服务器工夫
阐明:留神 timeStr 值,此时咱们把它当做 UTC 工夫,所以 time.LoadLocation("UTC") 应用 Local
## 工夫比拟
```go
timeLayout := "2006-01-02 15:04:05"
```
```go
timeStr := "2021-05-17 11:00:00" // 认为服务器工夫
location, _ := time.LoadLocation("Local") // timeStr 是北京工夫,留神应用 Local
localTime, _ := time.ParseInLocation(timeLayout, timeStr, location)
fmt.Println(localTime.UTC().Format(timeLayout)) // 转为 UTC 工夫
compareTimeStr := "2021-05-17 02:00:00" // 认为 UTC 工夫
location, _ = time.LoadLocation("UTC") // timeStr 是北京工夫,留神应用 UTC
compareTime, _ := time.ParseInLocation(timeLayout, compareTimeStr, location)
fmt.Println(compareTime.Local().Format(timeLayout)) // 转为服务器工夫
fmt.Println("------------------------------------")
fmt.Println(compareTime.Before(localTime)) // Before 会对立工夫基准点
fmt.Println(compareTime.After(localTime)) // After 会对立工夫基准点
```