-
Notifications
You must be signed in to change notification settings - Fork 73
/
datetime.go
66 lines (50 loc) · 1.5 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
package ari
import (
"encoding/json"
"strconv"
"time"
)
// NOTE: near direct translation from ARI 2.0
// DateFormat is the date format that ARI returns in the JSON bodies
const DateFormat = "2006-01-02T15:04:05.000-0700"
// DateTime is an alias type for attaching a custom
// asterisk unmarshaller and marshaller for JSON
type DateTime time.Time
// MarshalJSON converts the given date object to ARIs date format
func (dt DateTime) MarshalJSON() ([]byte, error) {
a := []byte("\"" + time.Time(dt).Format(DateFormat) + "\"")
return a, nil
}
// UnmarshalJSON parses the given date per ARIs date format
func (dt *DateTime) UnmarshalJSON(data []byte) error {
var stringDate string
if err := json.Unmarshal(data, &stringDate); err != nil {
return err
}
t, err := time.Parse(DateFormat, stringDate)
if err != nil {
return err
}
*dt = (DateTime)(t)
return nil
}
func (dt DateTime) String() string {
t := (time.Time)(dt)
return t.String()
}
// Duration support functions
// DurationSec is a JSON type for duration in seconds
type DurationSec time.Duration
// MarshalJSON converts the duration into a JSON friendly format
func (ds DurationSec) MarshalJSON() ([]byte, error) {
return []byte(strconv.Itoa(int(time.Duration(ds) / time.Second))), nil
}
// UnmarshalJSON parses the data into the duration seconds object
func (ds *DurationSec) UnmarshalJSON(data []byte) error {
s, err := strconv.Atoi(string(data))
if err != nil {
return err
}
*ds = DurationSec(time.Duration(s) * time.Second)
return nil
}