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