为了账号安全,请及时绑定邮箱和手机立即绑定

为什么围棋时间。格式根据时区返回不同的值?

为什么围棋时间。格式根据时区返回不同的值?

Go
开心每一天1111 2022-08-15 10:50:50
我以为是围棋时间。格式应根据布局设置时间格式。但似乎它根据时区信息返回不同的值。package mainimport (    "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 versiongo version go1.15 darwin/amd64➜ TZ=UTC go run main.goFormat: 2006-01-02T15:04:05Z07:00unix: 1583661590000000000time: 2020-03-08T01:59:50-08:00time + 1s: 2020-03-08T01:59:51-08:00Format: 2006-01-02T15:04:05Z07:00unix: 1583661599000000000time: 2020-03-08T01:59:59-08:00time + 1s: 2020-03-08T02:00:00-08:00 (a: this is not expected)unix: 1583675999000000000time: 2020-03-08T05:59:59-08:00time + 1s: 2020-03-08T06:00:00-08:00➜ TZ=America/Los_Angeles go run main.goFormat: 2006-01-02T15:04:05Z07:00unix: 1583661590000000000time: 2020-03-08T01:59:50-08:00time + 1s: 2020-03-08T01:59:51-08:00Format: 2006-01-02T15:04:05Z07:00 unix: 1583661599000000000time: 2020-03-08T01:59:59-08:00time + 1s: 2020-03-08T03:00:00-07:00 (b: this is expected)Format: 2006-01-02T15:04:05Z07:00unix: 1583675999000000000time: 2020-03-08T05:59:59-08:00time + 1s: 2020-03-08T06:00:00-08:00 (c: this contradicts with the b)
查看完整描述

1 回答

?
守候你守候我

TA贡献1802条经验 获得超10个赞

行为已记录在案。的输出只是一个结果,而不是混淆的来源 - 这是:time.Formattime.Parse

func Parse

使用区域偏移量(如 -0700)解析时间时,如果偏移量对应于当前位置(本地)使用的时区,则 Parse 将在返回的时间中使用该位置和区域。否则,它将时间记录为在制造位置,时间固定在给定的区域偏移处。

进一步的说明可以在类型位置下找到:

本地表示系统的本地时区。在 Unix 系统上,Local 会查阅 TZ 环境变量以查找要使用的时区。没有 TZ 意味着使用系统默认的 /etc/localtime。TZ=“” 表示使用 UTC。TZ=“foo” 表示在系统时区目录中使用文件 foo。

基本上,go的解析器试图从UTC偏移量推断时区。如果解析的 UTC 偏移量与环境变量设置的时区的偏移量匹配,则此时区将在返回的 中设置。在处理日期和时间时,简单性似乎总是结束。TZtime


查看完整回答
反对 回复 2022-08-15
  • 1 回答
  • 0 关注
  • 142 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号