datetime.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package types
  2. import (
  3. "database/sql/driver"
  4. "errors"
  5. "time"
  6. )
  7. // TimeText time text
  8. type TimeText string
  9. // DateText date text
  10. type DateText string
  11. // const
  12. const (
  13. timeFormat = `2006-01-02 15:04:05`
  14. dateFormat = `2006-01-02`
  15. )
  16. // Value implements the driver.Valuer interface
  17. func (t TimeText) Value() (driver.Value, error) {
  18. t1, err := time.ParseInLocation(timeFormat, string(t), time.Local)
  19. if err != nil {
  20. return nil, err
  21. }
  22. return TimeText(t1.Format(timeFormat)), nil
  23. }
  24. // Scan implements the sql.Scanner interface
  25. func (t *TimeText) Scan(src interface{}) error {
  26. v, ok := src.(time.Time)
  27. if !ok {
  28. return errors.New("bad time.Time type assertion")
  29. }
  30. *t = TimeText(v.Format(timeFormat))
  31. return nil
  32. }
  33. // Value implements the driver.Valuer interface
  34. func (t DateText) Value() (driver.Value, error) {
  35. t1, err := time.ParseInLocation(dateFormat, string(t), time.Local)
  36. if err != nil {
  37. return nil, err
  38. }
  39. return DateText(t1.Format(dateFormat)), nil
  40. }
  41. // Scan implements the sql.Scanner interface
  42. func (t *DateText) Scan(src interface{}) error {
  43. v, ok := src.(time.Time)
  44. if !ok {
  45. return errors.New("bad time.Time type assertion")
  46. }
  47. *t = DateText(v.Format(dateFormat))
  48. return nil
  49. }