time.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package time
  2. import (
  3. "database/sql/driver"
  4. "time"
  5. )
  6. type Time time.Time
  7. const (
  8. timeFormat = "2006-01-02 15:04:05"
  9. )
  10. func (t *Time) UnmarshalJSON(data []byte) (err error) {
  11. now, err := time.ParseInLocation(`"`+timeFormat+`"`, string(data), time.Local)
  12. *t = Time(now)
  13. return
  14. }
  15. func (t Time) MarshalJSON() ([]byte, error) {
  16. b := make([]byte, 0, len(timeFormat)+2)
  17. b = append(b, '"')
  18. b = time.Time(t).AppendFormat(b, timeFormat)
  19. b = append(b, '"')
  20. return b, nil
  21. }
  22. func (t Time) GobEncode() ([]byte, error) {
  23. return t.Time().MarshalBinary()
  24. }
  25. func (t Time) String() string {
  26. return time.Time(t).Format(timeFormat)
  27. }
  28. func (t Time) Time() time.Time {
  29. return time.Time(t)
  30. }
  31. func (t Time) IsZero() bool {
  32. return t.Time().IsZero()
  33. }
  34. func (t Time) After(u Time) bool {
  35. return t.Time().After(u.Time())
  36. }
  37. func (t Time) Before(u Time) bool {
  38. return t.Time().Before(u.Time())
  39. }
  40. func (t Time) Equal(u Time) bool {
  41. return t.Time().Equal(u.Time())
  42. }
  43. func (t Time) Add(d time.Duration) Time {
  44. return Time(t.Time().Add(d))
  45. }
  46. func (t Time) AddDate(years int, months int, days int) Time {
  47. return Time(t.Time().AddDate(years, months, days))
  48. }
  49. func (t Time) Sub(u Time) time.Duration {
  50. return t.Time().Sub(u.Time())
  51. }
  52. // 实现sql驱动
  53. func (t *Time) Scan(value interface{}) error {
  54. switch s := value.(type) {
  55. case time.Time:
  56. *t = Time(s)
  57. }
  58. return nil
  59. }
  60. //实现sql驱动
  61. func (t Time) Value() (driver.Value, error) {
  62. return t.Time(), nil
  63. }
  64. func Now() Time {
  65. t := time.Now()
  66. return Time(t)
  67. }