-
Notifications
You must be signed in to change notification settings - Fork 0
/
datetime.go
63 lines (51 loc) · 979 Bytes
/
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
package webservices
import (
"encoding/json"
"regexp"
"strconv"
"time"
)
type DateTime struct {
time.Time
}
func (d *DateTime) MarshalJSON() ([]byte, error) {
if d.Time.IsZero() {
return json.Marshal(nil)
}
return json.Marshal(d.Time)
}
func (d DateTime) IsEmpty() bool {
return d.Time.IsZero()
}
func (d *DateTime) UnmarshalJSON(text []byte) (err error) {
var value string
err = json.Unmarshal(text, &value)
if err != nil {
return err
}
if value == "" {
return nil
}
// first try standard date
d.Time, err = time.Parse(time.RFC3339, value)
if err == nil {
return nil
}
d.Time, err = time.Parse("2006-01-02", value)
if err == nil {
return nil
}
// /Date(1488939627017)/
re := regexp.MustCompile(`[0-9]+`)
match := re.FindString(value)
if match == "" {
return nil
}
milis, err := strconv.Atoi(match)
if err != nil {
return err
}
// new Date(milis)
d.Time = time.Unix(0, int64(milis)*int64(time.Millisecond))
return err
}