doudou5023 2017-05-02 15:04
浏览 40
已采纳

防止json.marshal time.time删除尾随零

I have code similar to the following

package main

import (
    "fmt"
    "time"
    "encoding/json"
)

type Message struct {
    Time time.Time `json:"timestamp,omitempty"`
}

func main() {
    t, _ := time.Parse("2006-01-02T15:04:05.999Z07:00", "2017-05-01T15:04:05.630Z")
    msg := Message{
        Time: t,
    }
    bs, _ := json.Marshal(msg)
    fmt.Println(string(bs[:]))
}

This prints

{"timestamp":"2017-05-01T15:04:05.63Z"}

How can I make json marshalling keep the trailing 0? I.e., to print this?

{"timestamp":"2017-05-01T15:04:05.630Z"}

Edit:

Here's the playground https://play.golang.org/p/9p3kWeiwu2

  • 写回答

1条回答 默认 最新

  • dsvf46980 2017-05-02 16:09
    关注

    time.Time always marshals to RFC 3339, only including sub-second precision if present: https://golang.org/pkg/time/#Time.MarshalJSON

    You can write your own custom version using a named time.Time type, or you can define a custom marshal function for your structure, or you can make your structure hold a string in that place instead. In any case, if you want to use the same format, but including trailing zeros, you need to use a modified version of the RFC3339Nano constant.

    Its value is: "2006-01-02T15:04:05.999999999Z07:00".

    The 9's at the end mean "include until the rightmost non-zero value, omit after that". If you change those 9's to 0's, it will always include them. For example, if you always want millisecond precision (and nothing after that, regardless of whether it's non-zero or not), you would use:

    "2006-01-02T15:04:05.000Z07:00"

    If you feed that to Format() on your time.Time value, you'll get out the string you want, and can thus include it in the JSON.

    Functioning example: https://play.golang.org/p/oqwnma6odw

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来