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

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

报告相同问题?

悬赏问题

  • ¥15 优质github账号直接兑换rmb,感兴趣伙伴可以私信
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)