请教一下关于 gorm 格式化时间的问题
1. 运行环境
go version go1.18 darwin/arm64
2. 问题描述?
article 模型文件
package model
type ArticleModel struct {
ArticleId uint `gorm:"primarykey" json:"article_id"`
Title string `gorm:"size:255" json:"title"`
CateId int8 `gorm:"size:255" json:"cate_id"`
Type int8 `gorm:"size:20" json:"type"`
Sort int8 `gorm:"size:20" json:"sort"`
Author string `gorm:"size:64" json:"author"`
Sources string `gorm:"size:1024" json:"sources"`
Content string `gorm:"type:longtext" json:"content"`
Timestamp
}
// TableName 自定义表名
func (ArticleModel) TableName() string {
return "demo_article"
}
自定义时间类型文件
package model
import (
"database/sql/driver"
"fmt"
"time"
)
type Timestamp struct {
CreatedAt LocalTime `json:"created_at" gorm:"type:timestamp"`
UpdatedAt LocalTime `json:"updated_at" gorm:"type:timestamp"`
}
type LocalTime time.Time
func (t *LocalTime) MarshalJSON() ([]byte, error) {
tTime := time.Time(*t)
return []byte(fmt.Sprintf("\"%v\"", tTime.Format("2006-01-02 15:04:05"))), nil
}
func (t LocalTime) Value() (driver.Value, error) {
var zeroTime time.Time
tlt := time.Time(t)
// 判断给定时间是否和默认零时间的时间戳相同
if tlt.UnixNano() == zeroTime.UnixNano() {
return nil, nil
}
return tlt, nil
}
func (t *LocalTime) Scan(v interface{}) error {
if value, ok := v.(time.Time); ok {
*t = LocalTime(value)
return nil
}
return fmt.Errorf("can not convert %v to timestamp", v)
}
func (t *LocalTime) String() string {
return fmt.Sprintf("hhh:%s", time.Time(*t).String())
}
方法一查询单条记录
var articleModel model.ArticleModel
global.DB.First(&articleModel)
方法二查询多条记录
var articleModel []model.ArticleModel
global.DB.Scopes(db.Paginate(params.Page, params.PageSize)).Order("article_id Desc").Find(&articleModel)
方法一和二的结果最后用 json 返回,发现方法一无法格式化时间,方法二却可以
3. 您实际得到的结果?
方法一的接口数据返回
方法二的接口数据返回
可以发现方法一查询单条的时候没有被格式化,发现没有执行 MarshalJSON 方法,打印了数据created_at 和 updated_at 结果是
{{047352819 0x10536cc20}}}
问题原因