time.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package initialize
  2. import (
  3. "database/sql/driver"
  4. "fmt"
  5. "time"
  6. )
  7. const timeFormat = "2006-01-02 15:04:05"
  8. const timezone = "Asia/Shanghai"
  9. // 全局定义
  10. type Time time.Time
  11. func (t Time) MarshalJSON() ([]byte, error) {
  12. b := make([]byte, 0, len(timeFormat)+2)
  13. if time.Time(t).IsZero() {
  14. b = append(b, '"')
  15. b = append(b, '"')
  16. return b, nil
  17. }
  18. b = append(b, '"')
  19. b = time.Time(t).AppendFormat(b, timeFormat)
  20. b = append(b, '"')
  21. return b, nil
  22. }
  23. func (t *Time) UnmarshalJSON(data []byte) (err error) {
  24. now, err := time.ParseInLocation(`"`+timeFormat+`"`, string(data), time.Local)
  25. *t = Time(now)
  26. return
  27. }
  28. func (t Time) String() string {
  29. if time.Time(t).IsZero() {
  30. return ""
  31. }
  32. return time.Time(t).Format(timeFormat)
  33. }
  34. func (t Time) Local() time.Time {
  35. loc, _ := time.LoadLocation(timezone)
  36. return time.Time(t).In(loc)
  37. }
  38. func (t Time) Value() (driver.Value, error) {
  39. var zeroTime time.Time
  40. var ti = time.Time(t)
  41. if ti.UnixNano() == zeroTime.UnixNano() {
  42. return nil, nil
  43. }
  44. return ti, nil
  45. }
  46. func (t *Time) Scan(v interface{}) error {
  47. value, ok := v.(time.Time)
  48. if ok {
  49. *t = Time(value)
  50. return nil
  51. }
  52. return fmt.Errorf("can not convert %v to timestamp", v)
  53. }