4
golang gorm mysql 读写时间戳
source link: https://studygolang.com/articles/35245
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
golang gorm mysql 读写时间戳
eflight · 2天之前 · 100 次点击 · 预计阅读时间 2 分钟 · 大约8小时之前 开始浏览gorm直接写time.Time类型时,会报错
在打开数据库命令中加入parseTime=true&loc=Local
例如:root:1234567@tcp(127.0.0.1:3306)/dbName?charset=utf8&parseTime=true&loc=Local&timeout=1000ms
自定义自己的time类型,用于数据库读写
package types
import (
"database/sql/driver"
"fmt"
"time"
)
// Time is alias type for time.Time
type Time time.Time
const (
timeFormart = "2006-01-02 15:04:05"
zone = "Asia/Shanghai"
)
// UnmarshalJSON implements json unmarshal interface.
func (t *Time) UnmarshalJSON(data []byte) (err error) {
now, err := time.ParseInLocation(`"`+timeFormart+`"`, string(data), time.Local)
*t = Time(now)
return
}
// MarshalJSON implements json marshal interface.
func (t Time) MarshalJSON() ([]byte, error) {
b := make([]byte, 0, len(timeFormart)+2)
b = append(b, '"')
b = time.Time(t).AppendFormat(b, timeFormart)
b = append(b, '"')
return b, nil
}
func (t Time) String() string {
return time.Time(t).Format(timeFormart)
}
func (t Time) local() time.Time {
loc, _ := time.LoadLocation(zone)
return time.Time(t).In(loc)
}
// Value ...
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
}
// Scan valueof time.Time 注意是指针类型 method
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)
}
原理 自定义数据库数据类型,在 sql driver 中实现自定义类型需要实现 Scanner和Valuer接口
Scanner
type Scanner interface {
Scan(src interface{}) error
}
Valuer
type Valuer interface {
// Value returns a driver Value.
Value() (Value, error)
}
unmarshal和marshal 自定义 json 转换格式
本文用作学习笔记,参考转载了 gorm 处理时间戳 的内容,如若侵权,请联系删除。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK