timestamp.go 834 B

123456789101112131415161718192021222324252627282930313233343536
  1. package packngo
  2. import (
  3. "strconv"
  4. "time"
  5. )
  6. // Timestamp represents a time that can be unmarshalled from a JSON string
  7. // formatted as either an RFC3339 or Unix timestamp. All
  8. // exported methods of time.Time can be called on Timestamp.
  9. type Timestamp struct {
  10. time.Time
  11. }
  12. func (t Timestamp) String() string {
  13. return t.Time.String()
  14. }
  15. // UnmarshalJSON implements the json.Unmarshaler interface.
  16. // Time is expected in RFC3339 or Unix format.
  17. func (t *Timestamp) UnmarshalJSON(data []byte) (err error) {
  18. str := string(data)
  19. i, err := strconv.ParseInt(str, 10, 64)
  20. if err == nil {
  21. t.Time = time.Unix(i, 0)
  22. } else {
  23. t.Time, err = time.Parse(`"`+time.RFC3339+`"`, str)
  24. }
  25. return
  26. }
  27. // Equal reports whether t and u are equal based on time.Equal
  28. func (t Timestamp) Equal(u Timestamp) bool {
  29. return t.Time.Equal(u.Time)
  30. }