time.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package utils
  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. // Time 全局定义
  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. }
  54. type BaseModel struct {
  55. ID uint `gorm:"primary_key" json:"id"`
  56. CreatedAt Time
  57. UpdatedAt Time
  58. DeletedAt *Time `sql:"index"`
  59. }