推荐
关注
TOP
Message

Golang Gorm time 时间字段格式化模型类 重写

问题:

在使用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
}

func (t Time) String() string {
    return time.Time(t).Format(timeFormat)
}

func (t Time) local() time.Time {
    loc, _ := time.LoadLocation(timezone)
    return time.Time(t).In(loc)
}

func (t Time) Value() (driver.Value, error) {
    var zeroTime time.Time
    var ti = time.Time(t)
    if ti.UnixNano() == zeroTime.UnixNano() {
        return nil, nil
    }
    return ti, nil
}

func (t *Time) Scan(v interface{}) error {
    value, ok := v.(time.Time)
    if ok {
        *t = Time(value)
        return nil
    }
    return fmt.Errorf("can not convert %v to timestamp", v)
}

调用

至于调用就更简单了 如下代码所示


package model

type Category struct {
	//*gorm.Model
	ID       uint      `json:"id" gorm:"primary key"`
	Name     string    `json:"name" gorm:"type:varchar(50); not null;unique"`
	CreatedAt Time     `json:"create_at"`
	UpdatedAt Time     `json:"update_at"`
}

posted @ 2022-10-13 16:44  始識  阅读(665)  评论(0编辑  收藏  举报