【发布时间】:2021-06-02 14:04:51
【问题描述】:
我认为 Go time.Format 应该根据布局格式化时间。但似乎它会根据时区信息返回不同的值。
package main
import (
"fmt"
"time"
)
func main() {
formats := []string{
time.RFC3339,
}
times := []string{
"2020-03-08T01:59:50-08:00",
"2020-03-08T01:59:59-08:00", //daylight saving starts 1 second later
"2020-03-08T05:59:59-08:00",
}
for _, f := range formats {
for _, t := range times {
fmt.Printf("Format: %s\n", f)
t, err := time.Parse(f, t)
if err != nil {
panic(err)
}
fmt.Printf("unix: %d\n", t.UnixNano())
fmt.Printf("time: %s\n", t.Format(f))
t = t.Add(time.Second)
fmt.Printf("time + 1s: %s\n", t.Format(f))
}
}
}
运行输出:
➜ go version
go version go1.15 darwin/amd64
➜ TZ=UTC go run main.go
Format: 2006-01-02T15:04:05Z07:00
unix: 1583661590000000000
time: 2020-03-08T01:59:50-08:00
time + 1s: 2020-03-08T01:59:51-08:00
Format: 2006-01-02T15:04:05Z07:00
unix: 1583661599000000000
time: 2020-03-08T01:59:59-08:00
time + 1s: 2020-03-08T02:00:00-08:00 (a: this is not expected)
unix: 1583675999000000000
time: 2020-03-08T05:59:59-08:00
time + 1s: 2020-03-08T06:00:00-08:00
➜ TZ=America/Los_Angeles go run main.go
Format: 2006-01-02T15:04:05Z07:00
unix: 1583661590000000000
time: 2020-03-08T01:59:50-08:00
time + 1s: 2020-03-08T01:59:51-08:00
Format: 2006-01-02T15:04:05Z07:00
unix: 1583661599000000000
time: 2020-03-08T01:59:59-08:00
time + 1s: 2020-03-08T03:00:00-07:00 (b: this is expected)
Format: 2006-01-02T15:04:05Z07:00
unix: 1583675999000000000
time: 2020-03-08T05:59:59-08:00
time + 1s: 2020-03-08T06:00:00-08:00 (c: this contradicts with the b)
【问题讨论】:
-
为什么不期望该值?
UTC没有夏令时,所以格式化的时间是正确的。 -
再看看这个,我会说
2020-03-08T03:00:00-07:00是结果我没想到...看起来很奇怪我认为可以通过这种方式设置时区。我的意思是,我希望程序解析一个字符串——它没有时区信息,只是一个偏移量!那么为什么要神秘地引入 DST 更改呢? -
谢谢大家!更新以包含新时间。还是一头雾水。