Debian Codegraph @

util/iso6801.go

raw symbols SCIP
1 package util
2
3 import (
4 "fmt"
5 "strconv"
6 "time"
7 )
8
9 // GetISO8601TimeStamp gets timestamp string in ISO8601 format
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 // A ISO6801Time represents a time in ISO8601 format
21 type ISO6801Time time.Time
22
23 // New constructs a new iso8601.Time instance from an existing
24 // time.Time instance. This causes the nanosecond field to be set to
25 // 0, and its time zone set to a fixed zone with no offset from UTC
26 // (but it is *not* UTC itself).
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 // IsDefault checks if the time is default
41 func (it *ISO6801Time) IsDefault() bool {
42 return *it == ISO6801Time{}
43 }
44
45 // MarshalJSON serializes the ISO6801Time into JSON string
46 func (it ISO6801Time) MarshalJSON() ([]byte, error) {
47 return []byte(time.Time(it).Format(jsonFormatISO8601)), nil
48 }
49
50 // UnmarshalJSON deserializes the ISO6801Time from JSON string
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 // String returns the time in ISO6801Time format
78 func (it ISO6801Time) String() string {
79 return time.Time(it).Format(formatISO8601)
80 }