forked from blacklightcms/recurly
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtype_null_time.go
75 lines (62 loc) · 1.81 KB
/
type_null_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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package recurly
import (
"encoding/json"
"encoding/xml"
"time"
)
// DateTimeFormat is the format Recurly uses to represent datetimes.
const DateTimeFormat = "2006-01-02T15:04:05Z07:00"
// NullTime is used for properly handling time.Time types that could be null.
type NullTime struct {
*time.Time
Raw string `xml:",innerxml"`
}
// NewTime generates a new NullTime.
func NewTime(t time.Time) NullTime {
t = t.UTC()
return NullTime{Time: &t}
}
// NewTimeFromString generates a new NullTime based on a
// time string in the DateTimeFormat format.
// This is primarily used in unit testing.
func NewTimeFromString(str string) NullTime {
t, _ := time.Parse(DateTimeFormat, str)
return NullTime{Time: &t}
}
// UnmarshalXML unmarshals an int properly, as well as marshaling an empty string to nil.
func (t *NullTime) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
var v string
err := d.DecodeElement(&v, &start)
if err == nil && v != "" {
parsed, err := time.Parse(DateTimeFormat, v)
if err != nil {
return err
}
*t = NewTime(parsed)
}
return nil
}
// MarshalJSON method has to be added here due to embeded interface json marshal issue in Go
// with panic on nil time field
func (t NullTime) MarshalJSON() ([]byte, error) {
if t.Time != nil {
return json.Marshal(t.Time)
}
return []byte("null"), nil
}
// MarshalXML marshals times into their proper format. Otherwise nothing is
// marshaled. All times are sent in UTC.
func (t NullTime) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
if t.Time != nil {
e.EncodeElement(t.String(), start)
}
return nil
}
// String returns a string representation of the time in UTC using the
// DateTimeFormat constant as the format.
func (t NullTime) String() string {
if t.Time != nil {
return t.Time.UTC().Format(DateTimeFormat)
}
return ""
}