package dts import ( "database/sql" "database/sql/driver" "encoding/json" "time" ) type NullDate struct { Date time.Time Valid bool // Valid is true if Date is not NULL } func (date NullDate) Any() any { if date.Valid { return date.Date } return nil } func (nd *NullDate) Scan(value any) error { if value == nil { nd.Date, nd.Valid = time.Time{}, false return nil } nt := new(sql.NullTime) err := nt.Scan(value) nd.Date = nt.Time nd.Valid = nt.Valid return err } func (nd NullDate) Value() (driver.Value, error) { if !nd.Valid { return nil, nil } y, m, d := nd.Date.Date() return time.Date(y, m, d, 0, 0, 0, 0, nd.Date.Location()), nil } // GormDataType gorm common data type func (nd NullDate) GormDataType() string { return "date" } func (nd NullDate) MarshalJSON() ([]byte, error) { if nd.Valid { return nd.Date.MarshalJSON() } return json.Marshal(nil) } func (nd *NullDate) UnmarshalJSON(b []byte) error { if string(b) == "null" { nd.Valid = false return nil } err := nd.Date.UnmarshalJSON(b) if err == nil { nd.Valid = true } return err }