time.go 853 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package types
  2. import (
  3. "database/sql/driver"
  4. "errors"
  5. "time"
  6. )
  7. // DateText is an implementation of a string for the MySQL type date.
  8. type DateText string
  9. const (
  10. formtDate = `2006-01-02`
  11. )
  12. // Value implements the driver.Valuer interface,
  13. // and turns the date into a DateText (date) for MySQL storage.
  14. func (d DateText) Value() (driver.Value, error) {
  15. t, err := time.Parse(formtDate, string(d))
  16. if err != nil {
  17. return nil, err
  18. }
  19. return DateText(t.Format(formtDate)), nil
  20. }
  21. // Scan implements the sql.Scanner interface,
  22. // and turns the bitfield incoming from MySQL into a Date
  23. func (d *DateText) Scan(src interface{}) error {
  24. v, ok := src.([]byte)
  25. if !ok {
  26. return errors.New("bad []byte type assertion")
  27. }
  28. t, err := time.Parse(formtDate, string(v))
  29. if err != nil {
  30. return err
  31. }
  32. *d = DateText(t.Format(formtDate))
  33. return nil
  34. }