go-time-parse-error

踩坑

go time.Parse 有坑

比如这种不带时区的时间 2021-07-02 12:13:14

1
2
3
4
5
6
7
8
9
10
11
12
package main

import (
"fmt"
"time"
)

func main() {
t, _ := time.Parse("2006-01-02 15:04:05", "2021-07-02 12:13:14")
fmt.Println(t)
// 2021-07-02 12:13:14 +0000 UTC
}

返回的是utc时间

可以根据自己程序中的时区,使用 time.ParseInLocation 来解决

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

import (
"fmt"
"time"
)

func main() {
t, _ := time.ParseInLocation("2006-01-02 15:04:05", "2021-07-02 12:13:14", time.Local)
fmt.Println(t)
// 2021-07-02 12:13:14 +0800 CST

}
0%