-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
date.go
45 lines (38 loc) · 918 Bytes
/
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
package commercetools
import (
"encoding/json"
"fmt"
"strconv"
"time"
)
// Date holds date information for Commercetools API format
type Date struct {
Year int
Month time.Month
Day int
}
// NewDate initializes a Date struct
func NewDate(year int, month time.Month, day int) Date {
return Date{Year: year, Month: month, Day: day}
}
// MarshalJSON marshals into the commercetools date format
func (d *Date) MarshalJSON() ([]byte, error) {
value := fmt.Sprintf("%04d-%02d-%02d", d.Year, d.Month, d.Day)
return []byte(strconv.Quote(value)), nil
}
// UnmarshalJSON decodes JSON data into a Date struct
func (d *Date) UnmarshalJSON(data []byte) error {
var input string
err := json.Unmarshal(data, &input)
if err != nil {
return err
}
value, err := time.Parse("2006-01-02", input)
if err != nil {
return err
}
d.Year = value.Year()
d.Month = value.Month()
d.Day = value.Day()
return nil
}