讨论数量:
// app/modles/modle.go
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
}
// CommonTimestampsField 时间戳
type CommonTimestampsField struct {
CreatedAt *LocalTime `gorm:"type:datetime(0);column:created_at;index;autoCreateTime" json:"created_at,omitempty"`
UpdatedAt *LocalTime `gorm:"type:datetime(0);column:updated_at;index;autoUpdateTime" json:"updated_at,omitempty"`
}
我个人一直在使用的更加优雅的做法,参见下文:
app/models/model.go
// Package models 模型通用属性和方法
package models
import (
"github.com/spf13/cast"
)
// BaseModel 模型基类
type BaseModel struct {
ID uint64 `gorm:"column:id;primaryKey;autoIncrement;" json:"id,omitempty"`
}
// CommonTimestampsField 时间戳
type CommonTimestampsField struct {
CreatedAt *JSONTime `gorm:"type:datetime(0);column:created_at;index;autoCreateTime" json:"created_at,omitempty"`
UpdatedAt *JSONTime `gorm:"type:datetime(0);column:updated_at;index;autoUpdateTime" json:"updated_at,omitempty"`
}
// GetStringID 获取 ID 的字符串格式
func (a BaseModel) GetStringID() string {
return cast.ToString(a.ID)
}
app/models/model_time.go(该文件请自行创建)
// Package models 模型通用属性和方法
package models
import (
"database/sql/driver"
"fmt"
"time"
)
// JSONTime format json time field by myself
type JSONTime struct {
time.Time
}
// MarshalJSON on JSONTime format Time field with %Y-%m-%d %H:%M:%S
func (t JSONTime) MarshalJSON() ([]byte, error) {
formatted := fmt.Sprintf("\"%s\"", t.Format("2006-01-02 15:04:05"))
return []byte(formatted), nil
}
// Value insert timestamp into mysql need this function.
func (t JSONTime) Value() (driver.Value, error) {
var zeroTime time.Time
if t.Time.UnixNano() == zeroTime.UnixNano() {
return nil, nil
}
return t.Time, nil
}
// Scan valueof time.Time
func (t *JSONTime) Scan(v interface{}) error {
value, ok := v.(time.Time)
if ok {
*t = JSONTime{Time: value}
return nil
}
return fmt.Errorf("can not convert %v to timestamp", v)
}
// New on JSONTime format Time field with %Y-%m-%d %H:%M:%S
func (t JSONTime) New() JSONTime {
return JSONTime{Time: time.Now()}
}
可解决模型的统一自定义时间显示和数据库插入,仅供参考。
推荐文章: