| 1 |
package util |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"strconv" |
| 6 |
"time" |
| 7 |
) |
| 8 |
|
| 9 |
|
| 10 |
func GetISO8601TimeStamp(ts time.Time) string { |
| 11 |
t := ts.UTC() |
| 12 |
return fmt.Sprintf("%04d-%02d-%02dT%02d:%02d:%02dZ", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second()) |
| 13 |
} |
| 14 |
|
| 15 |
const formatISO8601 = "2006-01-02T15:04:05Z" |
| 16 |
const jsonFormatISO8601 = `"` + formatISO8601 + `"` |
| 17 |
const formatISO8601withoutSeconds = "2006-01-02T15:04Z" |
| 18 |
const jsonFormatISO8601withoutSeconds = `"` + formatISO8601withoutSeconds + `"` |
| 19 |
|
| 20 |
|
| 21 |
type ISO6801Time time.Time |
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
func NewISO6801Time(t time.Time) ISO6801Time { |
| 28 |
return ISO6801Time(time.Date( |
| 29 |
t.Year(), |
| 30 |
t.Month(), |
| 31 |
t.Day(), |
| 32 |
t.Hour(), |
| 33 |
t.Minute(), |
| 34 |
t.Second(), |
| 35 |
0, |
| 36 |
time.UTC, |
| 37 |
)) |
| 38 |
} |
| 39 |
|
| 40 |
|
| 41 |
func (it *ISO6801Time) IsDefault() bool { |
| 42 |
return *it == ISO6801Time{} |
| 43 |
} |
| 44 |
|
| 45 |
|
| 46 |
func (it ISO6801Time) MarshalJSON() ([]byte, error) { |
| 47 |
return []byte(time.Time(it).Format(jsonFormatISO8601)), nil |
| 48 |
} |
| 49 |
|
| 50 |
|
| 51 |
func (it *ISO6801Time) UnmarshalJSON(data []byte) error { |
| 52 |
str := string(data) |
| 53 |
|
| 54 |
if str == "\"\"" || len(data) == 0 { |
| 55 |
return nil |
| 56 |
} |
| 57 |
var t time.Time |
| 58 |
var err error |
| 59 |
if str[0] == '"' { |
| 60 |
t, err = time.ParseInLocation(jsonFormatISO8601, str, time.UTC) |
| 61 |
if err != nil { |
| 62 |
t, err = time.ParseInLocation(jsonFormatISO8601withoutSeconds, str, time.UTC) |
| 63 |
} |
| 64 |
} else { |
| 65 |
var i int64 |
| 66 |
i, err = strconv.ParseInt(str, 10, 64) |
| 67 |
if err == nil { |
| 68 |
t = time.Unix(i/1000, i%1000) |
| 69 |
} |
| 70 |
} |
| 71 |
if err == nil { |
| 72 |
*it = ISO6801Time(t) |
| 73 |
} |
| 74 |
return err |
| 75 |
} |
| 76 |
|
| 77 |
|
| 78 |
func (it ISO6801Time) String() string { |
| 79 |
return time.Time(it).Format(formatISO8601) |
| 80 |
} |