-
Notifications
You must be signed in to change notification settings - Fork 216
/
timestamp.go
70 lines (62 loc) · 1.94 KB
/
timestamp.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
package types
import (
"encoding/json"
"encoding/xml"
"fmt"
"time"
)
// Timestamp wraps time.Time to normalize the time layout to RFC3339. It is
// intended to enforce compliance with the CloudEvents spec for their
// definition of Timestamp. Custom marshal methods are implemented to ensure
// the outbound Timestamp is a string in the RFC3339 layout.
type Timestamp struct {
time.Time
}
// ParseTimestamp attempts to parse the given time assuming RFC3339 layout
func ParseTimestamp(s string) (*Timestamp, error) {
if s == "" {
return nil, nil
}
tt, err := ParseTime(s)
return &Timestamp{Time: tt}, err
}
// MarshalJSON implements a custom json marshal method used when this type is
// marshaled using json.Marshal.
func (t *Timestamp) MarshalJSON() ([]byte, error) {
if t == nil || t.IsZero() {
return []byte(`""`), nil
}
return []byte(fmt.Sprintf("%q", t)), nil
}
// UnmarshalJSON implements the json unmarshal method used when this type is
// unmarshaled using json.Unmarshal.
func (t *Timestamp) UnmarshalJSON(b []byte) error {
var timestamp string
if err := json.Unmarshal(b, ×tamp); err != nil {
return err
}
var err error
t.Time, err = ParseTime(timestamp)
return err
}
// MarshalXML implements a custom xml marshal method used when this type is
// marshaled using xml.Marshal.
func (t *Timestamp) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
if t == nil || t.IsZero() {
return e.EncodeElement(nil, start)
}
return e.EncodeElement(t.String(), start)
}
// UnmarshalXML implements the xml unmarshal method used when this type is
// unmarshaled using xml.Unmarshal.
func (t *Timestamp) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
var timestamp string
if err := d.DecodeElement(×tamp, &start); err != nil {
return err
}
var err error
t.Time, err = ParseTime(timestamp)
return err
}
// String outputs the time using RFC3339 format.
func (t Timestamp) String() string { return FormatTime(t.Time) }