time.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package hook
  2. import (
  3. "database/sql/driver"
  4. "encoding/json"
  5. "fmt"
  6. "time"
  7. "gorm.io/gorm"
  8. )
  9. const (
  10. LocalDateTimeFormat string = "2006-01-02 15:04:05"
  11. )
  12. type LocalTime time.Time
  13. // Scan 实现了 LocalTime 的 Scanner
  14. func (l *LocalTime) Scan(v interface{}) error {
  15. value, ok := v.(time.Time)
  16. if ok {
  17. *l = LocalTime(value)
  18. return nil
  19. }
  20. return fmt.Errorf("cannot convert %v to timestamp", v)
  21. }
  22. // Value 实现了 LocalTime 的 driver.Valuer
  23. func (l LocalTime) Value() (driver.Value, error) {
  24. if l.IsZero() {
  25. return nil, nil // Handle zero value case
  26. }
  27. return time.Time(l).Format(LocalDateTimeFormat), nil
  28. }
  29. // MarshalText 实现了 LocalTime 的 MarshalText
  30. func (l LocalTime) MarshalText() (text []byte, err error) {
  31. b := make([]byte, 0, len(LocalDateTimeFormat))
  32. b = time.Time(l).AppendFormat(b, LocalDateTimeFormat)
  33. if string(b) == `0001-01-01 00:00:00` {
  34. b = []byte(``)
  35. }
  36. return b, nil
  37. }
  38. // IsZero 实现了 LocalTime 的 IsZero
  39. func (l LocalTime) IsZero() bool {
  40. return time.Time(l).IsZero()
  41. }
  42. // UnmarshalJSON 实现了 LocalTime 的 UnmarshalJSON
  43. type DeletedAtWrapper struct {
  44. *gorm.DeletedAt
  45. }
  46. // "2006-01-02 15:04:05"
  47. func (d *DeletedAtWrapper) MarshalJSON() ([]byte, error) {
  48. if d == nil {
  49. return []byte("null"), nil
  50. }
  51. return json.Marshal(d.Time.Format(LocalDateTimeFormat))
  52. }
  53. func (t *LocalTime) UnmarshalJSON(data []byte) error {
  54. var expireTimeStr string
  55. err := json.Unmarshal(data, &expireTimeStr)
  56. if err != nil {
  57. return err
  58. }
  59. expireTime, err := time.Parse("2006-01-02 15:04:05", expireTimeStr)
  60. if err != nil {
  61. return err
  62. }
  63. *t = LocalTime(expireTime)
  64. return nil
  65. }