-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatetime.go
86 lines (71 loc) · 1.54 KB
/
datetime.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
76
77
78
79
80
81
82
83
84
85
86
package twigots
import (
"encoding/json"
"strconv"
"time"
)
const (
dateTimeLayout = "2006-01-02T15:04:05Z"
dateLayout = "2006-01-02"
timeLayout = "15:04:05"
)
// DateTime is a date and time.
type DateTime struct{ time.Time }
func (dt *DateTime) UnmarshalJSON(data []byte) error {
var dateTimeString string
err := json.Unmarshal(data, &dateTimeString)
if err != nil {
return err
}
parsedDateTime, err := time.Parse(dateTimeLayout, dateTimeString)
if err != nil {
return err
}
dt.Time = parsedDateTime
return nil
}
// Date is a date (with no time).
type Date struct{ time.Time }
func (d *Date) UnmarshalJSON(data []byte) error {
var dateString string
err := json.Unmarshal(data, &dateString)
if err != nil {
return err
}
parsedDate, err := time.Parse(dateLayout, dateString)
if err != nil {
return err
}
d.Time = parsedDate
return nil
}
// Date is a time (with no date).
type Time struct{ time.Time }
func (t *Time) UnmarshalJSON(data []byte) error {
var timeString string
err := json.Unmarshal(data, &timeString)
if err != nil {
return err
}
parsedTime, err := time.Parse(timeLayout, timeString)
if err != nil {
return err
}
t.Time = parsedTime
return nil
}
// UnixTime is a time from unix time.
type UnixTime struct{ time.Time }
func (t *UnixTime) UnmarshalJSON(data []byte) error {
var timeString string
err := json.Unmarshal(data, &timeString)
if err != nil {
return err
}
timeInt, err := strconv.Atoi(timeString)
if err != nil {
return err
}
t.Time = time.UnixMilli(int64(timeInt))
return nil
}