使用 time.Unix() 和 time.Parse() 初始化的 time.Time 具有完全相同的 unix 时间戳,使用 time.Format("2006-01-02") 打印出不同的结果
问题在 playground 中无法重现,但如果我自己编译就可以解决。
我的默认时区是洛杉矶,可能在不同的时区结果会不同。
go version go version go1.12.1 darwin/amd64
go build
./test
测试.go:
package main
import (
"fmt"
"time"
)
func main() {
control1 := time.Unix(1546300800, 0)
test, _ := time.Parse("2006-01-02", "2019-01-01")
fmt.Println("control:", control1.Unix(), control1.Format("2006-01-02"))
fmt.Println("test:", test.Unix(), test.Format("2006-01-02"))
}
./test control: 1546300800 2018-12-31 test: 1546300800 2019-01-01
所以unix ts是一样的(1546300800),只是日期不同。为什么?
最佳答案
打印的日期不同,因为它们有不同的时区。
time.Unix()
返回本地时间,而time.Parse()
:
Elements omitted from the value are assumed to be zero or, when zero is impossible, one, so parsing "3:04pm" returns the time corresponding to Jan 1, year 0, 15:04:00 UTC (note that because the year is 0, this time is before the zero Time).
time.Parse()
返回一个 time.Time
默认有 UTC
时区(如果时区信息不是输入的一部分并且布局)。
这也解释了为什么你在 Go Playground 上看不到它:本地时间有 UTC。
在我的本地计算机(CET 时区)中打印时区信息:
fmt.Println("control:", control1.Unix(), control1.Format("2006-01-02 -0700"))
fmt.Println("test :", test.Unix(), test.Format("2006-01-02 -0700"))
fmt.Println(control1.Zone())
fmt.Println(test.Zone())
输出:
control: 1546300800 2019-01-01 +0100
test : 1546300800 2019-01-01 +0000
CET 3600
UTC 0
如果您将两个时间都切换到同一个时区(例如 UTC
或本地),打印的日期将是相同的:
control1 = control1.UTC()
test = test.UTC()
在此之后,输出:
control: 1546300800 2019-01-01 +0000
test : 1546300800 2019-01-01 +0000
UTC 0
UTC 0
关于golang time.Format() 对相同的 unix 时间戳给出不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56456111/