@@ -10,9 +10,9 @@ import (
1010)
1111
1212type Datetime struct {
13- Val time.Time
14- Null bool
15- Set bool
13+ Val time.Time
14+ Valid bool
15+ Set bool
1616}
1717
1818func loadLocation() (*time.Location, error) {
@@ -39,16 +39,16 @@ func Now(layout string) string {
3939func NewDatetime(v string) Datetime {
4040 t, err := parseDatetime(v)
4141 if err != nil {
42- return Datetime{Null: true, Set: true}
42+ return Datetime{Set: true}
4343 }
44- return Datetime{Val: *t, Set: true}
44+ return Datetime{Val: *t, Valid: true, Set: true}
4545}
4646
4747func NewNullableDatetime(v *string) Datetime {
4848 if v != nil {
4949 return NewDatetime(*v)
5050 }
51- return Datetime{Null: true, Set: true}
51+ return Datetime{Set: true}
5252}
5353
5454// Scan implements the Scanner interface.
@@ -58,7 +58,7 @@ func (d *Datetime) Scan(value interface{}) error {
5858 if err != nil {
5959 return err
6060 }
61- d.Val, d.Null = n.Time, ! n.Valid
61+ d.Val, d.Valid = n.Time, n.Valid
6262 loc, err := loadLocation()
6363 if err != nil {
6464 return err
@@ -69,15 +69,15 @@ func (d *Datetime) Scan(value interface{}) error {
6969
7070// Value implements the driver Valuer interface.
7171func (d Datetime) Value() (driver.Value, error) {
72- if d.Null {
72+ if !d.Valid {
7373 return nil, nil
7474 }
7575 return d.Val.UTC(), nil
7676}
7777
7878// MarshalJSON implements the json.Marshaler interface.
7979func (d Datetime) MarshalJSON() ([]byte, error) {
80- if d.Null {
80+ if !d.Valid {
8181 return json.Marshal(nil)
8282 }
8383 return json.Marshal(d.Val.UTC())
@@ -88,10 +88,9 @@ func (d *Datetime) UnmarshalJSON(data []byte) error {
8888 d.Set = true
8989 s := string(data)
9090 if s == "null" || s == "" {
91- d.Null = true
9291 return nil
9392 }
94-
93+ d.Valid = true
9594 t := time.Time{}
9695 err := t.UnmarshalJSON(data)
9796 if err != nil {
@@ -106,3 +105,11 @@ func (d *Datetime) UnmarshalJSON(data []byte) error {
106105
107106 return nil
108107}
108+
109+ // String implements the stringer interface.
110+ func (d Datetime) String() string {
111+ if !d.Valid {
112+ return "null"
113+ }
114+ return d.Val.Format("2006-01-02 15:04:05")
115+ }
0 commit comments