timestamp.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package protocol
  2. import (
  3. "strconv"
  4. "time"
  5. )
  6. // Names of time formats supported by the SDK
  7. const (
  8. RFC822TimeFormatName = "rfc822"
  9. ISO8601TimeFormatName = "iso8601"
  10. UnixTimeFormatName = "unixTimestamp"
  11. )
  12. // Time formats supported by the SDK
  13. const (
  14. // RFC 7231#section-7.1.1.1 timetamp format. e.g Tue, 29 Apr 2014 18:30:38 GMT
  15. RFC822TimeFormat = "Mon, 2 Jan 2006 15:04:05 GMT"
  16. // RFC3339 a subset of the ISO8601 timestamp format. e.g 2014-04-29T18:30:38Z
  17. ISO8601TimeFormat = "2006-01-02T15:04:05Z"
  18. )
  19. // IsKnownTimestampFormat returns if the timestamp format name
  20. // is know to the SDK's protocols.
  21. func IsKnownTimestampFormat(name string) bool {
  22. switch name {
  23. case RFC822TimeFormatName:
  24. fallthrough
  25. case ISO8601TimeFormatName:
  26. fallthrough
  27. case UnixTimeFormatName:
  28. return true
  29. default:
  30. return false
  31. }
  32. }
  33. // FormatTime returns a string value of the time.
  34. func FormatTime(name string, t time.Time) string {
  35. t = t.UTC()
  36. switch name {
  37. case RFC822TimeFormatName:
  38. return t.Format(RFC822TimeFormat)
  39. case ISO8601TimeFormatName:
  40. return t.Format(ISO8601TimeFormat)
  41. case UnixTimeFormatName:
  42. return strconv.FormatInt(t.Unix(), 10)
  43. default:
  44. panic("unknown timestamp format name, " + name)
  45. }
  46. }
  47. // ParseTime attempts to parse the time given the format. Returns
  48. // the time if it was able to be parsed, and fails otherwise.
  49. func ParseTime(formatName, value string) (time.Time, error) {
  50. switch formatName {
  51. case RFC822TimeFormatName:
  52. return time.Parse(RFC822TimeFormat, value)
  53. case ISO8601TimeFormatName:
  54. return time.Parse(ISO8601TimeFormat, value)
  55. case UnixTimeFormatName:
  56. v, err := strconv.ParseFloat(value, 64)
  57. if err != nil {
  58. return time.Time{}, err
  59. }
  60. return time.Unix(int64(v), 0), nil
  61. default:
  62. panic("unknown timestamp format name, " + formatName)
  63. }
  64. }