问题:
在使用GORM中 如果我们使用到了CreateAt 和UpdateAt 就会发现 这个时间的类型是time.Time 而其数据是
"2022-10-13T10:14:02.973528+08:00" 这样的,
然而这样的数据你说能用确实能用 ,但是一旦写入数据库中就变成了
0001-01-01 00:00:00.000000 +00:00
重写数据类型
话不多说 直接上代码
并且此代码通用【小弟也是copy学习视频上的】
package model
import (
"database/sql/driver"
"fmt"
"time"
)
const timeFormat = "2006-01-02 15:04:05"
const timezone = "Asia/Shanghai"
type Time time.Time
func (t Time) MarshalJSON() ([]byte, error) {
b := make([]byte, 0, len(timeFormat)+2)
b = append(b, '"')
b = time.Time(t).AppendFormat(b, timeFormat)
b = append(b, '"')
return b, nil
}
func (t *Time) UnmarshalJSON(data []byte) (err error) {
now, err := time.ParseInLocation(`"`+timeFormat+`"`, string(data), time.Local)
*t = Time(now)
return
}

本文介绍了一种在GORM中优化处理CreateAt和UpdateAt时间字段的方法,通过自定义时间类型,解决了时间格式不一致的问题,并确保了数据库中时间数据的正确显示。
最低0.47元/天 解锁文章
3984

被折叠的 条评论
为什么被折叠?



