gpt4 book ai didi

macos - Golang JSON 时间默认布局因平台而异?

转载 作者:IT王子 更新时间:2023-10-29 01:42:41 25 4
gpt4 key购买 nike

我遇到了一个奇怪的问题,即 time.Time 的 JSON 编码字符串在我的开发环境 (OSX) 和生产环境 (Ubuntu 14.04 x64) 之间有所不同。

type Thang struct {
CreatedAt time.Time `json:"created_at"`
}

操作系统:

{
// RFC3339 layout
created_at: "2015-04-24T22:39:59Z",
}

Ubuntu 14.04 x64:

{
// RFC3339Nano layout
created_at: "2015-05-21T15:00:46.546000003Z",
}

我一直在谷歌上搜索。想不通这一点。这里有更多信息:

  • 这是一个直接的网络服务应用
  • 在我的 OSX 机器上运行 go 1.4.1
  • 我在我的 OSX 机器上交叉编译应用程序以进行部署,如下所示:
    • GOOS=linux GOARCH=amd64 go build

非常感谢任何见解!

最佳答案

time.TimeMarshalJSON 的来源是:

// MarshalJSON implements the json.Marshaler interface.
// The time is a quoted string in RFC 3339 format, with sub-second precision added if present.
func (t Time) MarshalJSON() ([]byte, error) {
if y := t.Year(); y < 0 || y >= 10000 {
// RFC 3339 is clear that years are 4 digits exactly.
// See golang.org/issue/4556#c15 for more discussion.
return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]")
}
return []byte(t.Format(`"` + RFC3339Nano + `"`)), nil
}

[ time.MarshalJSON source on GitHub ]

并且在所有平台上都是一样的。注意:

[…] with sub-second precision added if present.

RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"。“9”的意思是使用最多那么多数字,但删除尾随零。所以看起来你的两个例子都可以匹配这种格式。(当解析时间时,无论格式如何,Go 总是接受并解析小数秒)。

RFC3339 的第 5.6 节指定小数秒是可选的,可以包括也可以不包括(只是说如果小数点存在,它必须后跟至少一位数字)。

出于某种原因,您在一个系统上使用的时间是否只有秒级或类似的精度? (例如,这是否来自某些文件系统或其他仅在其中一个操作系统上存储秒数的子系统?)。

关于macos - Golang JSON 时间默认布局因平台而异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30413324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com