-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtime.go
50 lines (41 loc) · 989 Bytes
/
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
package model
import (
"encoding/json"
"fmt"
"strings"
"time"
)
// There are multiple time formats coming back from the API
const (
// 2021-07-20T01:40:11.187+0000
TimeFormat = "2006-01-02T15:04:05.999-0700"
// 2021-07-20T01:40:09.560+00:00
TimeFormat2 = "2006-01-02T15:04:05.999-07:00"
)
type ModzyTime struct {
time.Time
}
var _ json.Unmarshaler = &ModzyTime{}
var _ json.Marshaler = &ModzyTime{}
func (mt *ModzyTime) UnmarshalJSON(b []byte) error {
clean := strings.Trim(string(b), `"`)
if clean == "null" {
return nil
}
for _, df := range []string{TimeFormat, TimeFormat2} {
if t, err := time.Parse(df, clean); err == nil {
*mt = ModzyTime{Time: t}
return nil
}
}
return fmt.Errorf("failed to parse modzy time: %s", clean)
}
func (mt ModzyTime) MarshalJSON() ([]byte, error) {
if mt.IsZero() {
return []byte("null"), nil
}
return []byte(fmt.Sprintf(`"%s"`, mt)), nil
}
func (mt ModzyTime) String() string {
return mt.Time.Format(TimeFormat)
}