-
Notifications
You must be signed in to change notification settings - Fork 27
/
Date.go
87 lines (67 loc) · 1.8 KB
/
Date.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
87
package connect
import (
"encoding/json"
"fmt"
"strconv"
"time"
)
// Date represents a single day in Garmin Connect.
type Date struct {
Year int
Month time.Month
DayOfMonth int
}
// Time returns a time.Time for usage in other packages.
func (d Date) Time() time.Time {
return time.Date(d.Year, d.Month, d.DayOfMonth, 0, 0, 0, 0, time.UTC)
}
// UnmarshalJSON implements json.Unmarshaler.
func (d *Date) UnmarshalJSON(value []byte) error {
if string(value) == "null" {
return nil
}
// Sometimes dates are transferred as milliseconds since epoch :-/
i, err := strconv.ParseInt(string(value), 10, 64)
if err == nil {
t := time.Unix(i/1000, 0)
d.Year, d.Month, d.DayOfMonth = t.Date()
return nil
}
var blip string
err = json.Unmarshal(value, &blip)
if err != nil {
return err
}
_, err = fmt.Sscanf(blip, "%04d-%02d-%02d", &d.Year, &d.Month, &d.DayOfMonth)
if err != nil {
return err
}
return nil
}
// MarshalJSON implements json.Marshaler.
func (d Date) MarshalJSON() ([]byte, error) {
// To better support the Garmin API we marshal the empty value as null.
if d.Year == 0 && d.Month == 0 && d.DayOfMonth == 0 {
return []byte("null"), nil
}
return []byte(fmt.Sprintf("\"%04d-%02d-%02d\"", d.Year, d.Month, d.DayOfMonth)), nil
}
// ParseDate will parse a date in the format yyyy-mm-dd.
func ParseDate(in string) (Date, error) {
d := Date{}
_, err := fmt.Sscanf(in, "%04d-%02d-%02d", &d.Year, &d.Month, &d.DayOfMonth)
return d, err
}
// String implements Stringer.
func (d Date) String() string {
if d.Year == 0 && d.Month == 0 && d.DayOfMonth == 0 {
return "-"
}
return fmt.Sprintf("%04d-%02d-%02d", d.Year, d.Month, d.DayOfMonth)
}
// Today will return a Date set to today.
func Today() Date {
d := Date{}
d.Year, d.Month, d.DayOfMonth = time.Now().Date()
return d
}