1
0

json_time.go 916 B

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