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 with fractional second precision up to milliseconds 31 ISO8601OutputTimeFormat = "2006-01-02T15:04:05.999999999Z" 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().Truncate(time.Millisecond) 52 53 switch name { 54 case RFC822TimeFormatName: 55 return t.Format(RFC822OutputTimeFormat) 56 case ISO8601TimeFormatName: 57 return t.Format(ISO8601OutputTimeFormat) 58 case UnixTimeFormatName: 59 ms := t.UnixNano() / int64(time.Millisecond) 60 return strconv.FormatFloat(float64(ms)/1e3, 'f', -1, 64) 61 default: 62 panic("unknown timestamp format name, " + name) 63 } 64} 65 66// ParseTime attempts to parse the time given the format. Returns 67// the time if it was able to be parsed, and fails otherwise. 68func ParseTime(formatName, value string) (time.Time, error) { 69 switch formatName { 70 case RFC822TimeFormatName: 71 return time.Parse(RFC822TimeFormat, value) 72 case ISO8601TimeFormatName: 73 return time.Parse(ISO8601TimeFormat, value) 74 case UnixTimeFormatName: 75 v, err := strconv.ParseFloat(value, 64) 76 _, dec := math.Modf(v) 77 dec = sdkmath.Round(dec*1e3) / 1e3 //Rounds 0.1229999 to 0.123 78 if err != nil { 79 return time.Time{}, err 80 } 81 return time.Unix(int64(v), int64(dec*(1e9))), nil 82 default: 83 panic("unknown timestamp format name, " + formatName) 84 } 85} 86