前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >go 结构体转 json 时, 日期类型转换

go 结构体转 json 时, 日期类型转换

作者头像
北漂的我
发布2021-06-22 20:56:48
1.3K0
发布2021-06-22 20:56:48
举报
文章被收录于专栏:北漂的我北漂的我

自定义一个 日期类型 DateTime 然后实现 Marshaler 接口的 MarshalJSON() 方法

代码语言:javascript
复制
package main

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

type DateTime time.Time

func (d DateTime) MarshalJSON() ([]byte, error) {
	dateTime := fmt.Sprintf("%q", time.Time(d).Format("2006-01-02 15:04:05"))
	return []byte(dateTime), nil
}

type Tom struct {
	Name     string   `json:"name"`
	Age      int      `json:"age"`
	Birthday DateTime `json:"birthday"`
}

func main() {
	tom := Tom{
		Name:     "tom",
		Age:      25,
		Birthday: DateTime(time.Now()),
	}
	bytes, err := json.Marshal(tom)
	if err == nil {
		fmt.Println(string(bytes))
	}
}

结果为

代码语言:javascript
复制
{"name":"tom","age":25,"birthday":"2021-06-18 15:04:03"}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档