-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtimestamp.go
49 lines (46 loc) · 1.22 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
package patrol
import (
"fmt"
"strings"
"time"
)
type Timestamp struct {
time.Time
TimestampFormat string
}
func (self *Timestamp) UnmarshalJSON(
data []byte,
) error {
// if our object is nil, we're going to end up using Parse(time.RFC3339) since UnmarshalJSON by default uses this!!!
f := ""
if self.TimestampFormat == "" {
f = time.RFC3339
} else {
f = self.TimestampFormat
}
s := strings.Trim(string(data), "\"")
if s == "" || s == "null" {
self.Time = time.Time{}
return nil
}
t, err := time.Parse(f, s)
if err != nil {
return err
}
self.Time = t
return nil
}
func (self Timestamp) MarshalJSON() ([]byte, error) {
// if our object is nil, we're going to end up using Format(time.RFC3339) since UnmarshalJSON by default uses this!!!
if self.TimestampFormat == "" {
return []byte(fmt.Sprintf("\"%s\"", self.Time.Format(time.RFC3339))), nil
}
return []byte(fmt.Sprintf("\"%s\"", self.Time.Format(self.TimestampFormat))), nil
}
func (self Timestamp) String() string {
// if our object is nil, we're going to end up using Format(time.RFC3339) since UnmarshalJSON by default uses this!!!
if self.TimestampFormat == "" {
return self.Time.Format(time.RFC3339)
}
return self.Time.Format(self.TimestampFormat)
}