使用它可以解决以下问题:
type Timeline struct {
ID string `json:"id"`
Timestamp *time.Time `json:"timestamp" gorm:"type:datetime"`
}
您甚至可以更改
Timestamp
比如说,字段
int64
表示Unix时代。然后,您可以编写一个扫描器,将datetime字段读入int64字段。
type TimeStampUnix int64
type Timeline struct {
ID string `json:"id"`
TimeStamp TimeStampUnix `json:"timestamp" gorm:"type:datetime"`
}
func (t *TimeStampUnix) Scan(src interface{}) error {
switch src.(type) {
case time.Time:
*t = TimeStampUnix(src.(time.Time).Unix())
return nil
case []byte:
// bonus code to read text field of format '2014-12-31 14:21:01-0400'
//
str := string(src.([]byte))
var y, m, d, hr, min, s, tzh, tzm int
var sign rune
_, e := fmt.Sscanf(str, "%d-%d-%d %d:%d:%d%c%d:%d",
&y, &m, &d, &hr, &min, &s, &sign, &tzh, &tzm)
if e != nil {
return e
}
offset := 60 * (tzh*60 + tzm)
if sign == '-' {
offset = -1 * offset
}
loc := time.FixedZone("local-tz", offset)
t1 := time.Date(y, time.Month(m), d, hr, min, s, 0, loc)
*t = TimeStampUnix(t1.Unix())
return nil
default:
return fmt.Errorf("Value '%s' of incompatible type '%T' found", string(src.([]byte)), src)
}
}