nulltime.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package utils
  2. import (
  3. "database/sql/driver"
  4. "fmt"
  5. "time"
  6. )
  7. // NullTime is a custom nullable time for representing datetime.
  8. type NullTime struct {
  9. Time time.Time
  10. Valid bool // Valid is true if Time is not NULL
  11. }
  12. // Scan implements the Scanner interface.
  13. func (nt *NullTime) Scan(value interface{}) error {
  14. nt.Time, nt.Valid = value.(time.Time)
  15. return nil
  16. }
  17. // Value implements the driver Value interface.
  18. func (nt NullTime) Value() (driver.Value, error) {
  19. if !nt.Valid {
  20. return nil, nil
  21. }
  22. return nt.Time, nil
  23. }
  24. // MarshalJSON implements the JSON marshal function.
  25. func (nt NullTime) MarshalJSON() ([]byte, error) {
  26. if !nt.Valid {
  27. return []byte("null"), nil
  28. }
  29. val := fmt.Sprintf("\"%s\"", nt.Time.Format(time.RFC3339))
  30. return []byte(val), nil
  31. }
  32. // UnmarshalJSON implements the JSON unmarshal function.
  33. func (nt NullTime) UnmarshalJSON(data []byte) error {
  34. dateString := string(data)
  35. if dateString == "null" {
  36. return nil
  37. }
  38. dateStringWithoutQuotes := dateString[1 : len(dateString)-1]
  39. parsedDateTime, err := time.Parse(time.RFC3339, dateStringWithoutQuotes)
  40. if err != nil {
  41. return err
  42. }
  43. nt.Time = parsedDateTime // nolint
  44. return nil
  45. }