gin 返回 json time.Time 的问题

2022-11-17 14:36:02 +08:00
 woyao396
r := gin.Default()
r.GET("/time", func(c *gin.Context) {

		c.JSON( http.StatusOK, gin.H{
			"now": time.Now(),
		})
	})

返回

{
    "now": "2022-11-17T14:31:44.6111772+08:00"
}

就想定义 now 为 time.Time 不想定义为 string 然后 format

有 2 个疑问

  1. 为什么会带上毫秒、能取消掉吗?
  2. 有没有类似 spring boot 中的
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss

直接全局替换

1976 次点击
所在节点    Go 编程语言
12 条回复
wunonglin
2022-11-17 14:44:27 +08:00
time.Now().Format("22006-01-02 15:04:05")
chenqh
2022-11-17 14:45:27 +08:00
写个返回 NowTimeStr 的函数?
rrfeng
2022-11-17 15:15:10 +08:00
就想定义 now 为 time.Time 不想定义为 string 然后 format
---------

你想马儿跑还不给吃草??

总要改一个地方。

可以这样:

type MyTime time.Time

func(mt *MyTime) Marshal() ([]byte,error) {
返回你想要的格式
}


然后 json 里定义 now 为 MyTime 类型。
icoming
2022-11-17 15:24:34 +08:00
@wunonglin 年数多了个 2 吧。。
wunonglin
2022-11-17 15:25:36 +08:00
@icoming #4 打多了一个 2
CEBBCAT
2022-11-17 17:31:48 +08:00
> 就想定义 now 为 time.Time 不想定义为 string 然后 format
这都哪跟哪啊? json.Marshaler 学了吗?
rootliang
2022-11-17 17:32:23 +08:00
猜测可能是因为,json 并没有 time.Time 类型,在序列化的时候分配了默认的 String 类型,time.Time 转换为 string 的时候,会自动使用 time 实现的 string()方法,就得到了上面的结果
swulling
2022-11-17 17:45:57 +08:00
自定义一个 time 类型,自己写 marshal 和 unmarshal

https://segmentfault.com/a/1190000022264001
janxin
2022-11-17 17:59:16 +08:00
@rootliang time.Time 的处理逻辑中会按照 Marshaler 接口实现
lysS
2022-11-17 18:23:14 +08:00
time.Time 就是 nano 时间戳加时区嘛。json 是要序列化成可读的啊。你不想要毫秒,就直接 parse 成字符串啊
gollwang
2022-11-18 11:02:51 +08:00
默认的 JSON 序列化用的 RFC3339Nano ,反序列化用的 RFC3339 ,不满意的话就自己重写
991894172
2022-12-07 10:38:21 +08:00
@swulling 学习了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/895941

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX