GORM 格式化时间字段
转载: https://blog.csdn.net/m0_38112165/article/details/119081947
package main
import (
"database/sql/driver"
"encoding/json"
"fmt"
"time"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type LocalTime struct {
time.Time
}
func (t LocalTime) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("\"%s\"", t.Format("2006-01-02 15:04:05"))), nil
}
func (t LocalTime) Value() (driver.Value, error) {
var zeroTime time.Time
if t.Time.UnixNano() == zeroTime.UnixNano() {
return nil, nil
}
return t.Time, nil
}
func (t *LocalTime) Scan(v interface{}) error {
value, ok := v.(time.Time)
if ok {
*t = LocalTime{Time: value}
return nil
}
return fmt.Errorf("can not convert %v to timestamp", v)
}
type Model struct {
CreatedAt *LocalTime `json:"create_time" grom:"autoCreateTime"`
UpdatedAt *LocalTime `json:"update_time"`
}
type Test struct {
ID uint `gorm:"primaryKey"`
Name string `json:"name" gorm:"column:name;type:varchar(255)"`
Model
}
func main() {
dsn := mysql.Open("root:root@tcp(10.20.0.200:3306)/test_code?charset=utf8&parseTime=True&loc=Local")
db, err := gorm.Open(dsn, &gorm.Config{})
if err != nil {
panic(err)
}
// db.AutoMigrate(&Test{})
// db.Model(&Test{}).Create(&Test{Name: "0001"})
var test Test = Test{ID: 1}
db.Model(&test).First(&test)
j, err := json.Marshal(&test)
if err != nil {
panic(err)
}
fmt.Printf("j: %v\n", string(j))
}