time.go 709 B

1234567891011121314151617181920212223242526272829303132333435
  1. package models
  2. import (
  3. "database/sql/driver"
  4. "fmt"
  5. "time"
  6. )
  7. type JSONTime time.Time
  8. func (t JSONTime) MarshalJSON() ([]byte, error) {
  9. ti := time.Time(t)
  10. tune := ti.Format(`"2006-01-02 15:04:05"`)
  11. return []byte(tune), nil
  12. }
  13. // Value insert timestamp into mysql need this function.
  14. func (t JSONTime) Value() (driver.Value, error) {
  15. var zeroTime time.Time
  16. ti := time.Time(t)
  17. if ti.UnixNano() == zeroTime.UnixNano() {
  18. return nil, nil
  19. }
  20. return ti, nil
  21. }
  22. // Scan ValueOf time.Time
  23. func (t *JSONTime) Scan(v interface{}) error {
  24. ti, ok := v.(time.Time) // NOT directly assertion v.(JSONTime)
  25. if ok {
  26. *t = JSONTime(ti)
  27. return nil
  28. }
  29. return fmt.Errorf("can not convert %v to timestamp", v)
  30. }