Gorm: 我想自定义模型json输出时间格式

Created on 14 Sep 2017  ·  2Comments  ·  Source: go-gorm/gorm

image
我这样自定义了时间类型,但是添加进数据库时,时间字段会为空

Most helpful comment

@shiguanghuxian
`// Value insert timestamp into mysql need this function.
func (ts TimeStamp) Value() (driver.Value, error) {
var zeroTime time.Time
var ti = time.Time(ts)
if ti.UnixNano() == zeroTime.UnixNano() {
return nil, nil
}
return ti, nil
}

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

All 2 comments

@shiguanghuxian
`// Value insert timestamp into mysql need this function.
func (ts TimeStamp) Value() (driver.Value, error) {
var zeroTime time.Time
var ti = time.Time(ts)
if ti.UnixNano() == zeroTime.UnixNano() {
return nil, nil
}
return ti, nil
}

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

Thank you. The problem has been settled
@hellojukay

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kumarsiva07 picture kumarsiva07  ·  3Comments

alanyuen picture alanyuen  ·  3Comments

koalacxr picture koalacxr  ·  3Comments

leebrooks0 picture leebrooks0  ·  3Comments

satb picture satb  ·  3Comments