dsykx64220 2015-05-23 13:34
浏览 32
已采纳

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

I'm having a strange issue where the JSON encoded string of a time.Time is varying between my development environment (OSX) and production environment (Ubuntu 14.04 x64).

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

OSX:

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

Ubuntu 14.04 x64:

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

I've googled around forever. Can't figure this one out. Here's some more info:

  • It's a straight forward web services app
  • Running go 1.4.1 on my OSX machine
  • I cross compile the app on my OSX machine for deployment like this:
    • GOOS=linux GOARCH=amd64 go build

Would appreciate any insight!

  • 写回答

2条回答 默认 最新

  • doze79040 2015-05-23 16:13
    关注

    The source for time.Time's MarshalJSON is:

    // 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]

    and is the same on all platforms. Note:

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

    And that RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00". The "9"'s mean use up-to that many digits but remove trailing zeros. So it looks like both your examples can match this format. (And when parsing times Go always accepts and parses fractional seconds no matter what the format says).

    Section 5.6 of RFC3339 specifies that the fractional seconds are optional and may or may not be included (only saying that if the decimal point is present it must be followed by at least one digit).

    For some reason does the time you're using on one system only have second accuracy or some such? (e.g. does this come from some filesystem or other sub-system that only stores seconds on one of the OSes?).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决