-
Notifications
You must be signed in to change notification settings - Fork 1
/
date.go
80 lines (66 loc) · 1.41 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
package scalar
import (
"encoding/json"
"time"
"github.com/hasura/ndc-sdk-go/utils"
)
const (
dateFormat = "2006-01-02"
)
// Date wraps the scalar implementation for date representation string
//
// @scalar Date date
type Date struct {
time.Time
}
// NewDate creates a date instance
func NewDate(year int, month time.Month, day int) *Date {
return &Date{
Time: time.Date(year, month, day, 0, 0, 0, 0, time.UTC),
}
}
// ParseDate parses a date from string
func ParseDate(value string) (*Date, error) {
t, err := time.Parse(dateFormat, value)
if err != nil {
return nil, err
}
return &Date{Time: t}, nil
}
// Stringer implements fmt.Stringer interface.
func (d Date) String() string {
return d.Format(dateFormat)
}
// MarshalJSON implements json.Marshaler.
func (d Date) MarshalJSON() ([]byte, error) {
return json.Marshal(d.String())
}
// UnmarshalJSON implements json.Unmarshaler.
func (d *Date) UnmarshalJSON(b []byte) error {
var value string
if err := json.Unmarshal(b, &value); err != nil {
return err
}
date, err := ParseDate(value)
if err != nil {
return err
}
*d = *date
return nil
}
// FromValue decode any value to d Date.
func (d *Date) FromValue(value any) error {
sValue, err := utils.DecodeNullableString(value)
if err != nil {
return err
}
if sValue == nil {
return nil
}
date, err := time.Parse(dateFormat, *sValue)
if err != nil {
return err
}
d.Time = date
return nil
}