-
Notifications
You must be signed in to change notification settings - Fork 0
/
json_time.go
61 lines (48 loc) · 1.17 KB
/
json_time.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package kittycad
import (
"bytes"
"time"
)
// Time is a wrapper around time.Time which marshals to and from empty strings.
type Time struct {
*time.Time
}
// MarshalJSON implements the json.Marshaler interface.
func (t Time) MarshalJSON() ([]byte, error) {
if t.Time == nil {
return []byte("null"), nil
}
return []byte(t.Format(`"` + time.RFC3339 + `"`)), nil
}
func (t Time) String() string {
if t.Time == nil {
return ""
}
return t.Format(`"` + time.RFC3339 + `"`)
}
// TimeNow returns the current time.
func TimeNow() Time {
now := time.Now()
return Time{&now}
}
// UnmarshalJSON implements the json.Unmarshaler interface.
// The time is expected to be a quoted string in RFC 3339 format.
func (t *Time) UnmarshalJSON(data []byte) (err error) {
// by convention, unmarshalers implement UnmarshalJSON([]byte("null")) as a no-op.
if bytes.Equal(data, []byte("null")) {
return nil
}
if bytes.Equal(data, []byte("")) {
return nil
}
if bytes.Equal(data, []byte(`""`)) {
return nil
}
// Fractional seconds are handled implicitly by Parse.
tt, err := time.Parse(`"`+time.RFC3339+`"`, string(data))
if err != nil {
return err
}
*t = Time{&tt}
return
}