自定义一个类型实现go时间类型的json和bson的序列化和反序列化

自定义一个类型实现go时间类型的json和bson的序列化和反序列化

需求

go语言在时间 和 json 转换时使用 yyyy-MM-dd HH:mm:ss 的格式,存到mongo时使用 时间戳(秒) 保存

实现 -自定义JSONTime类型

package JSONTime

import (
	"go.mongodb.org/mongo-driver/bson/bsontype"
	"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
	"time"
)

const (
	YYYYMMDD          = "2006-01-02"
	DefaultTimeFormat = "2006-01-02 15:04:05"
)

// 自定义 类型
type JSONTime struct {
	Time time.Time
}

//实现 json 的反序列方法
func (t *JSONTime) UnmarshalJSON(data []byte) (err error) {
	now, err := time.ParseInLocation(`"`+DefaultTimeFormat+`"`, string(data), time.Local)
	t.Time = now
	return
}

// 实现 json 的序列化方法
func (t JSONTime) MarshalJSON() ([]byte, error) {
	b := make([]byte, 0, len(DefaultTimeFormat)+2)
	b = append(b, '"')
	b = t.Time.AppendFormat(b, DefaultTimeFormat)
	b = append(b, '"')
	return b, nil
}

//初始化时间戳 2006-01-02 15:04:01
const INIT_TIMESTAMPT = 1136185440 

//实现 bson 的 序列化方法
func (t *JSONTime) MarshalBSONValue() (bsontype.Type, []byte, error) {
	timestampt := t.Time.Unix()
	if timestampt < 0 {
		timestampt = INIT_TIMESTAMPT
	}
	retByte := make([]byte, 0)
	retByte = bsoncore.AppendInt64(retByte, timestampt)
	return bsontype.Int64, retByte, nil
}

//实现 bson 的 反序列化方法
func (t *JSONTime) UnmarshalBSONValue(ty bsontype.Type, data []byte) error {
	if ty == bsontype.Int64 {
		if readInt64, _, ok := bsoncore.ReadInt64(data); ok {
			t.Time = time.Unix(readInt64, 0)
		}
	}
	return nil
}

如何使用?

type User struct {
	......
	CreatedAt JSONTime.JSONTime  `json:"created_at" bson:"created_at"`
	......
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值