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