|
| 1 | +package time |
| 2 | + |
| 3 | +import "time" |
| 4 | + |
| 5 | +// DeisDatetimeFormat is the standard date/time representation used in Deis. |
| 6 | +const DeisDatetimeFormat = "2006-01-02T15:04:05MST" |
| 7 | + |
| 8 | +// Different format to deal with the pyopenssl formatting |
| 9 | +// http://www.pyopenssl.org/en/stable/api/crypto.html#OpenSSL.crypto.X509.get_notAfter |
| 10 | +const PyOpenSSLTimeDateTimeFormat = "2006-01-02T15:04:05" |
| 11 | + |
| 12 | +// Time represents the standard datetime format used across the Deis Platform. |
| 13 | +type Time struct { |
| 14 | + *time.Time |
| 15 | +} |
| 16 | + |
| 17 | +func (t *Time) format() string { |
| 18 | + return t.Format(DeisDatetimeFormat) |
| 19 | +} |
| 20 | + |
| 21 | +// MarshalJSON implements the json.Marshaler interface. |
| 22 | +// The time is a quoted string in Deis' datetime format. |
| 23 | +func (t *Time) MarshalJSON() ([]byte, error) { |
| 24 | + return []byte(t.Format(`"` + DeisDatetimeFormat + `"`)), nil |
| 25 | +} |
| 26 | + |
| 27 | +// UnmarshalText implements the encoding.TextUnmarshaler interface. |
| 28 | +// The time is expected to be in Deis' datetime format. |
| 29 | +func (t *Time) UnmarshalText(data []byte) error { |
| 30 | + tt, err := time.Parse(time.RFC3339, string(data)) |
| 31 | + if _, ok := err.(*time.ParseError); ok { |
| 32 | + tt, err = time.Parse(DeisDatetimeFormat, string(data)) |
| 33 | + if _, ok := err.(*time.ParseError); ok { |
| 34 | + tt, err = time.Parse(PyOpenSSLTimeDateTimeFormat, string(data)) |
| 35 | + } |
| 36 | + } |
| 37 | + *t = Time{&tt} |
| 38 | + return err |
| 39 | +} |
| 40 | + |
| 41 | +// UnmarshalJSON implements the json.Unmarshaler interface. |
| 42 | +// The time is expected to be a quoted string in Deis' datetime format. |
| 43 | +func (t *Time) UnmarshalJSON(data []byte) error { |
| 44 | + // Fractional seconds are handled implicitly by Parse. |
| 45 | + tt, err := time.Parse(`"`+time.RFC3339+`"`, string(data)) |
| 46 | + if _, ok := err.(*time.ParseError); ok { |
| 47 | + tt, err = time.Parse(`"`+DeisDatetimeFormat+`"`, string(data)) |
| 48 | + if _, ok := err.(*time.ParseError); ok { |
| 49 | + tt, err = time.Parse(`"`+PyOpenSSLTimeDateTimeFormat+`"`, string(data)) |
| 50 | + } |
| 51 | + } |
| 52 | + *t = Time{&tt} |
| 53 | + return err |
| 54 | +} |
0 commit comments