package hook import ( "database/sql/driver" "encoding/json" "fmt" "time" "gorm.io/gorm" ) const ( LocalDateTimeFormat string = "2006-01-02 15:04:05" ) type LocalTime time.Time // Scan 实现了 LocalTime 的 Scanner func (l *LocalTime) Scan(v interface{}) error { value, ok := v.(time.Time) if ok { *l = LocalTime(value) return nil } return fmt.Errorf("cannot convert %v to timestamp", v) } // Value 实现了 LocalTime 的 driver.Valuer func (l LocalTime) Value() (driver.Value, error) { if l.IsZero() { return nil, nil // Handle zero value case } return time.Time(l).Format(LocalDateTimeFormat), nil } // MarshalText 实现了 LocalTime 的 MarshalText func (l LocalTime) MarshalText() (text []byte, err error) { b := make([]byte, 0, len(LocalDateTimeFormat)) b = time.Time(l).AppendFormat(b, LocalDateTimeFormat) if string(b) == `0001-01-01 00:00:00` { b = []byte(``) } return b, nil } // IsZero 实现了 LocalTime 的 IsZero func (l LocalTime) IsZero() bool { return time.Time(l).IsZero() } // UnmarshalJSON 实现了 LocalTime 的 UnmarshalJSON type DeletedAtWrapper struct { *gorm.DeletedAt } // "2006-01-02 15:04:05" func (d *DeletedAtWrapper) MarshalJSON() ([]byte, error) { if d == nil { return []byte("null"), nil } return json.Marshal(d.Time.Format(LocalDateTimeFormat)) } func (t *LocalTime) UnmarshalJSON(data []byte) error { var expireTimeStr string err := json.Unmarshal(data, &expireTimeStr) if err != nil { return err } expireTime, err := time.Parse("2006-01-02 15:04:05", expireTimeStr) if err != nil { return err } *t = LocalTime(expireTime) return nil }