datetime.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. // TimeText is an implementation of a string for the MySQL type datetime.
  10. type TimeText string
  11. const (
  12. formtDate = `2006-01-02`
  13. formtTime = `2006-01-02 15:04:05`
  14. )
  15. // Value implements the driver.Valuer interface,
  16. // and turns the date into a DateText (date) for MySQL storage.
  17. func (d DateText) Value() (driver.Value, error) {
  18. t, err := time.Parse(formtDate, string(d))
  19. if err != nil {
  20. return nil, err
  21. }
  22. return DateText(t.Format(formtDate)), nil
  23. }
  24. // Scan implements the sql.Scanner interface,
  25. // and turns the bitfield incoming from MySQL into a Date
  26. func (d *DateText) Scan(src interface{}) error {
  27. v, ok := src.([]byte)
  28. if !ok {
  29. return errors.New("bad []byte type assertion")
  30. }
  31. t, err := time.Parse(formtDate, string(v))
  32. if err != nil {
  33. return err
  34. }
  35. *d = DateText(t.Format(formtDate))
  36. return nil
  37. }
  38. // Value implements the driver.Valuer interface,
  39. // and turns the date into a DateText (date) for MySQL storage.
  40. func (d TimeText) Value() (driver.Value, error) {
  41. t, err := time.Parse(formtDate, string(d))
  42. if err != nil {
  43. return nil, err
  44. }
  45. return TimeText(t.Format(formtTime)), nil
  46. }
  47. // Scan implements the sql.Scanner interface,
  48. // and turns the bitfield incoming from MySQL into a Date
  49. func (d *TimeText) Scan(src interface{}) error {
  50. v, ok := src.([]byte)
  51. if !ok {
  52. return errors.New("bad []byte type assertion")
  53. }
  54. t, err := time.Parse(formtDate, string(v))
  55. if err != nil {
  56. return err
  57. }
  58. *d = TimeText(t.Format(formtTime))
  59. return nil
  60. }