github.com/aaabigfish/gopkg@v1.1.0/timex/xtime.go (about) 1 package timex 2 3 import ( 4 "database/sql/driver" 5 "fmt" 6 "time" 7 ) 8 9 type JsonTime time.Time 10 11 func (t JsonTime) MarshalJSON() ([]byte, error) { 12 s := fmt.Sprintf(`"%s"`, time.Time(t).Format(TimeLayout)) 13 return []byte(s), nil 14 } 15 16 func (t *JsonTime) UnmarshalJSON(data []byte) error { 17 if data == nil || len(data) <= 1 { 18 dateTime, _ := time.Parse(TimeLayout, "0000-00-00 00:00:00") 19 *t = JsonTime(dateTime) 20 return nil 21 } 22 // 因为实际接收到值是""2018-11-25 20:04:51""格式的,所以这里去除前后各一个"号 23 str := string(data[1 : len(data)-1]) 24 st, err := time.Parse(TimeLayout, str) 25 if err == nil { 26 *t = JsonTime(st) 27 } else { 28 return err 29 } 30 return nil 31 } 32 33 func (t JsonTime) Value() (driver.Value, error) { 34 tm := time.Time(t) 35 //return tm.Format(constant.TimeLayout), nil 36 return tm, nil 37 } 38 39 func (t *JsonTime) Scan(value interface{}) error { 40 if value == nil { 41 return nil 42 } 43 switch st := value.(type) { 44 case time.Time: 45 *t = JsonTime(st) 46 case string: 47 tm, err := time.Parse(TimeLayout, st) 48 if err != nil { 49 return err 50 } 51 *t = JsonTime(tm) 52 } 53 return nil 54 }