一、问题描述
在windows下,time.Parse()的时区和time.Format()的时区是一致的。
但是在linux环境下,time.Parse()的默认时区是UTC,time.Format()的时区默认是本地,两者如果不处理好就会导致错误。
1
2
3
4
5
6
7
8
9
10
11
12
13
package main
import "time"
import "fmt"
func main(){
t, err := time.Parse("2006年01月02日 15:04:05", "2017年12月03日 22:01:02")
if err != nil{
fmt.Println(err)
return
}
fmt.Println(t)
fmt.Println(time.Now())
fmt.Println(time.Now().Sub(t).Seconds())
}
输出:
1
2
3
2017年12月03日 22:01:02 +0000 UTC
2017年12月03日 22:15:26.592204446 +0800 CST m=+0.003020091
-27935.407549533
很明显能看到两者的时区不同并且如果把两者时间相减结果也不符合预期。
二、解决方法
使用time.ParseInLocation()而不是time.Parse():
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main
import "time"
import "fmt"
func main(){
localTime, err := time.ParseInLocation("2006年01月02日 15:04:05", "2017年12月03日 22:01:02", time.Local)
if err != nil{
fmt.Println(err)
return
}
fmt.Println(localTime)
fmt.Println(time.Now())
fmt.Println(time.Now().Sub(localTime).Seconds())
}
结果:
1
2
3
2017年12月03日 22:01:02 +0800 CST
2017年12月03日 22:18:26.288174547 +0800 CST m=+0.001532618
1044.288357362