datetime.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package model
  2. import (
  3. "encoding/json"
  4. "io"
  5. "log"
  6. "regexp"
  7. "strconv"
  8. "time"
  9. )
  10. type DateTime int64
  11. var datetimeLayout = "2006-01-02T15:04:05Z0700"
  12. func NewDateTime(milli int64) *DateTime {
  13. date := DateTime(milli)
  14. return &date
  15. }
  16. func NewDateTimeIn(seconds int) DateTime {
  17. return DateTime(
  18. time.Now().In(time.UTC).Add(time.Duration(seconds) * time.Second).UnixMilli())
  19. }
  20. func NewDateTimeFrom(t time.Time) *DateTime {
  21. date := DateTime(t.In(time.UTC).UnixMilli())
  22. return &date
  23. }
  24. func Now() DateTime {
  25. return DateTime(time.Now().In(time.UTC).UnixMilli())
  26. }
  27. func (d DateTime) String() string {
  28. return time.UnixMilli(int64(d)).In(time.UTC).Format(datetimeLayout)
  29. }
  30. func (d DateTime) MarshalJSON() ([]byte, error) {
  31. return json.Marshal(time.UnixMilli(int64(d)).In(time.UTC))
  32. }
  33. func (d DateTime) MarshalGQL(w io.Writer) {
  34. _, err := w.Write([]byte(strconv.Quote(d.String())))
  35. if err != nil {
  36. log.Default().Println(err)
  37. }
  38. }
  39. func (d *DateTime) UnixMilli() int64 {
  40. return int64(*d)
  41. }
  42. func (d *DateTime) UnmarshalGQL(v interface{}) error {
  43. switch v := v.(type) {
  44. case float64:
  45. *d = DateTime(v)
  46. case int:
  47. *d = DateTime(v)
  48. case time.Time:
  49. *d = DateTime(v.In(time.UTC).UnixMilli())
  50. case string:
  51. if regexp.MustCompile(`^\d{13}$`).MatchString(v) {
  52. if i, err := strconv.Atoi(v); err == nil {
  53. *d = DateTime(i)
  54. return nil
  55. }
  56. }
  57. t, err := time.Parse(datetimeLayout, v)
  58. if err != nil {
  59. return err
  60. }
  61. *d = DateTime(t.In(time.UTC).UnixMilli())
  62. case DateTime:
  63. *d = v
  64. }
  65. return nil
  66. }