time.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package model
  2. import (
  3. "database/sql/driver"
  4. "time"
  5. )
  6. // FormatTime format time
  7. type FormatTime string
  8. // NewFormatTime net formatTime
  9. func NewFormatTime(t time.Time) FormatTime {
  10. ft := new(FormatTime)
  11. ft.Scan(t)
  12. return *ft
  13. }
  14. // Scan scan time.
  15. func (jt *FormatTime) Scan(src interface{}) (err error) {
  16. switch sc := src.(type) {
  17. case time.Time:
  18. *jt = FormatTime(sc.Format("2006-01-02 15:04:05"))
  19. case string:
  20. *jt = FormatTime(sc)
  21. }
  22. return
  23. }
  24. // Value get string value.
  25. func (jt FormatTime) Value() (driver.Value, error) {
  26. return string(jt), nil
  27. }
  28. // TimeValue get time value.
  29. func (jt FormatTime) TimeValue() time.Time {
  30. t, _ := time.ParseInLocation("2006-01-02 15:04:05", string(jt), time.Local)
  31. if t.Unix() <= 0 {
  32. t, _ = time.ParseInLocation("2006-01-02 15:04:05", "0000-00-00 00:00:00", time.Local)
  33. }
  34. return t
  35. }
  36. // UnmarshalJSON implement Unmarshaler
  37. func (jt *FormatTime) UnmarshalJSON(data []byte) error {
  38. if data == nil || len(data) <= 1 {
  39. *jt = FormatTime("0000-00-00 00:00:00")
  40. return nil
  41. }
  42. str := string(data[1 : len(data)-1])
  43. st, err := time.Parse(time.RFC3339, str)
  44. if err == nil {
  45. *jt = FormatTime(st.Format("2006-01-02 15:04:05"))
  46. } else {
  47. *jt = FormatTime(str)
  48. }
  49. return nil
  50. }