**gorm直接写time.Time类型时,会报错**
#### 解决方案
1. 在打开数据库命令中加入**parseTime=true&loc=Local**
例如:**root:1234567@tcp(127.0.0.1:3306)/dbName?charset=utf8&parseTime=true&loc=Local&timeout=1000ms**
2. 自定义自己的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 处理时间戳](https://www.cnblogs.com/jssyjam/p/11695502.html) 的内容,如若侵权,请联系删除。
有疑问加站长微信联系(非本文作者))