ParseInLocation类似Parse但有两个重要的不同之处。第一,当缺少时区信息时,Parse将时间解释为UTC时间,而ParseInLocation将返回值的Location设置为loc;第二,当时间字符串提供了时区偏移量信息时,Parse会尝试去匹配本地时区,而ParseInLocation会去匹配loc。
func (t Time) In(loc *Location) Time
In返回采用loc指定的地点和时区,但指向同一时间点的Time。如果loc为nil会panic。
package main
import (
"fmt"
"time"
)
func main(){
t := "2019-10-10 10:10:10"
t1, _ := time.Parse("2006-01-02 15:04:05", t)
t2, _ := time.ParseInLocation("2006-01-02 15:04:05", t, time.Local)
fmt.Println(t1)
fmt.Println(t2)
fmt.Println(t1.Equal(t2))
var cstSh, _ = time.LoadLocation("Asia/Shanghai") //上海
fmt.Println("SH : ", time.Now().In(cstSh).Format("2006-01-02 15:04:05"))
//时区转换
fmt.Println("***************")
t = "2021-01-11T23:46:05Z"
t1, _ = time.Parse("2006-01-02T15:04:05Z", t)
fmt.Println(t)
fmt.Println("SH : ", t1.In(cstSh).Format("2006-01-02 15:04:05"))
}
结果:
2019-10-10 10:10:10 +0000 UTC
2019-10-10 10:10:10 +0800 CST
false
SH : 2021-01-18 17:01:40
***************
2021-01-11T23:46:05Z
SH : 2021-01-12 07:46:05