iso6801.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package util
  2. import (
  3. "fmt"
  4. "strconv"
  5. "time"
  6. )
  7. // GetISO8601TimeStamp gets timestamp string in ISO8601 format
  8. func GetISO8601TimeStamp(ts time.Time) string {
  9. t := ts.UTC()
  10. return fmt.Sprintf("%04d-%02d-%02dT%02d:%02d:%02dZ", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second())
  11. }
  12. const formatISO8601 = "2006-01-02T15:04:05Z"
  13. const jsonFormatISO8601 = `"` + formatISO8601 + `"`
  14. const formatISO8601withoutSeconds = "2006-01-02T15:04Z"
  15. const jsonFormatISO8601withoutSeconds = `"` + formatISO8601withoutSeconds + `"`
  16. // A ISO6801Time represents a time in ISO8601 format
  17. type ISO6801Time time.Time
  18. // New constructs a new iso8601.Time instance from an existing
  19. // time.Time instance. This causes the nanosecond field to be set to
  20. // 0, and its time zone set to a fixed zone with no offset from UTC
  21. // (but it is *not* UTC itself).
  22. func NewISO6801Time(t time.Time) ISO6801Time {
  23. return ISO6801Time(time.Date(
  24. t.Year(),
  25. t.Month(),
  26. t.Day(),
  27. t.Hour(),
  28. t.Minute(),
  29. t.Second(),
  30. 0,
  31. time.UTC,
  32. ))
  33. }
  34. // IsDefault checks if the time is default
  35. func (it *ISO6801Time) IsDefault() bool {
  36. return *it == ISO6801Time{}
  37. }
  38. // MarshalJSON serializes the ISO6801Time into JSON string
  39. func (it ISO6801Time) MarshalJSON() ([]byte, error) {
  40. return []byte(time.Time(it).Format(jsonFormatISO8601)), nil
  41. }
  42. // UnmarshalJSON deserializes the ISO6801Time from JSON string
  43. func (it *ISO6801Time) UnmarshalJSON(data []byte) error {
  44. str := string(data)
  45. if str == "\"\"" || len(data) == 0 {
  46. return nil
  47. }
  48. var t time.Time
  49. var err error
  50. if str[0] == '"' {
  51. t, err = time.ParseInLocation(jsonFormatISO8601, str, time.UTC)
  52. if err != nil {
  53. t, err = time.ParseInLocation(jsonFormatISO8601withoutSeconds, str, time.UTC)
  54. }
  55. } else {
  56. var i int64
  57. i, err = strconv.ParseInt(str, 10, 64)
  58. if err == nil {
  59. t = time.Unix(i/1000, i%1000)
  60. }
  61. }
  62. if err == nil {
  63. *it = ISO6801Time(t)
  64. }
  65. return err
  66. }
  67. // String returns the time in ISO6801Time format
  68. func (it ISO6801Time) String() string {
  69. return time.Time(it).Format(formatISO8601)
  70. }