jsonTime.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package util
  2. import (
  3. "database/sql/driver"
  4. "fmt"
  5. "time"
  6. )
  7. type JSON = map[string]interface{}
  8. // JSONTime format json time field by myself
  9. type JSONTime struct {
  10. time.Time
  11. }
  12. // MarshalJSON on JSONTime format Time field with %Y-%m-%d %H:%M:%S
  13. func (t JSONTime) UnmarshalJSON(b []byte) (err error) {
  14. t.Time, err = time.ParseInLocation(`"`+"2006-01-02 15:04:05"+`"`, string(b), time.Local)
  15. return
  16. }
  17. // MarshalJSON on JSONTime format Time field with %Y-%m-%d %H:%M:%S
  18. func (t JSONTime) MarshalJSON() ([]byte, error) {
  19. formatted := fmt.Sprintf("\"%s\"", t.Format("2006-01-02 15:04:05"))
  20. return []byte(formatted), nil
  21. }
  22. func (t JSONTime) String() string {
  23. return fmt.Sprintf("%s", t.Format("2006-01-02 15:04:05"))
  24. }
  25. // Value insert timestamp into mysql need this function.
  26. func (t JSONTime) Value() (driver.Value, error) {
  27. var zeroTime time.Time
  28. if t.Time.UnixNano() == zeroTime.UnixNano() {
  29. return nil, nil
  30. }
  31. return t.Time, nil
  32. }
  33. // Scan valueof time.Time
  34. func (t *JSONTime) Scan(v interface{}) error {
  35. value, ok := v.(time.Time)
  36. if ok {
  37. *t = JSONTime{Time: value}
  38. return nil
  39. }
  40. return fmt.Errorf("can not convert %v to timestamp", v)
  41. }