// LocalTime 继承time.Time类型 type LocalTime struct { time.Time } // 自定义的 layout var timeLayout string = "2006年01月02日 15:04:05"
// MarshalJSON json格式化时间的方法 // 在网上搜到的方式是格式化为时间戳的 不符合我的需求,这个方法是从 time源代码里找到的,直接修改默认 layout为自定义即可 func(t LocalTime)MarshalJSON()([]byte, error) { if y := t.Year(); y < 0 || y >= 10000 { // RFC 3339 is clear that years are 4 digits exactly. // See golang.org/issue/4556#c15 for more discussion. returnnil, errors.New("Time.MarshalJSON: year outside of range [0,9999]") } b := make([]byte, 0, len(timeLayout)+2) b = append(b, '"') b = t.AppendFormat(b, timeLayout) b = append(b, '"') return b, nil }
//下边两个方法是gorm需要,不需要修改,如果没有使用 gorm则不需要 // Value Value func(t LocalTime)Value()(driver.Value, error) { var zeroTime time.Time if t.Time.UnixNano() == zeroTime.UnixNano() { returnnil, nil } return t.Time, nil }
// Scan Scan func(t *LocalTime)Scan(v interface{})error { value, ok := v.(time.Time) if ok { *t = LocalTime{Time: value} returnnil } return fmt.Errorf("can not convert %v to timestamp", v) }