doushi3322 2016-04-18 05:55
浏览 82

json编码时间的可变秒数

So I have numerous structs which extend the gorm Model meaning they have createdAt, updatedAt and deletedAt time.Time fields. When I go to marshal these into JSON, the formats of the dates I receive vary. The proper RFC3339 timestamps it should produce look like:

2016-04-18T00:03:20Z

However, I am only getting dates formatted this way about 20% of the time. The remainder of the timestamps have a variable number of subseconds. I have received the following formats:

2016-04-18T05:51:11.54772087Z

2016-04-18T05:51:11.543835101Z

2016-04-18T05:53:20.1674444Z

Is there any way I can coerce Go into to giving me consistent timestamps? Thanks in advance!

  • 写回答

1条回答 默认 最新

  • doudun2212 2016-04-19 04:33
    关注

    The best way to control the output, is writing your own type. say type MyTime time.Time and implement Marshaller and Unmarshaller for it with your formatting. see time.MarshalJSON and time.UnmarshalJSON for hint. if you need this in a database column, implement the Scanner and Valuer on that too (see this answer). for other Marshaller/Unmarshaller you need to implement their interfaces (for example yaml/gob/...)

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大