-
Notifications
You must be signed in to change notification settings - Fork 0
/
datetime.go
97 lines (84 loc) · 1.99 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package types
import (
"fmt"
"io"
"strconv"
"time"
"github.com/99designs/gqlgen/graphql"
)
const dateTimeFormat = "2006-01-02T15:04:05.999999999Z"
// DateTime implements IO custom type of time with custom format
type DateTime time.Time
// DateTimeFromPtr returns DateTime object from pointer
func DateTimeFromPtr(tm *time.Time) DateTime {
if tm == nil {
return DateTime{}
}
return DateTime(*tm)
}
// GetTime object from DateTime
func (t DateTime) GetTime() time.Time {
return (time.Time)(t)
}
// SetTime from time object
func (t *DateTime) SetTime(tm time.Time) {
*t = (DateTime)(tm)
}
// MarshalGQL implements method of interface graphql.Marshaler
func (t DateTime) MarshalGQL(w io.Writer) {
_, _ = w.Write([]byte(strconv.Quote(
t.GetTime().Format(dateTimeFormat),
)))
}
// UnmarshalGQL implements method of interface graphql.Unmarshaler
func (t *DateTime) UnmarshalGQL(v any) error {
switch v := v.(type) {
case string:
tm, err := parseDate(v)
if err != nil {
return err
}
t.SetTime(tm)
return nil
default:
return fmt.Errorf("%T is not a supported as a date", v)
}
}
// MarshalTime redecalre the marshalel of standart scalar type Time
func MarshalTime(t time.Time) graphql.Marshaler {
return graphql.WriterFunc(func(w io.Writer) {
_, _ = io.WriteString(w, strconv.Quote(t.Format(dateTimeFormat)))
})
}
// UnmarshalTime redecalre the unmarshalel of standart scalar type Time
func UnmarshalTime(v any) (time.Time, error) {
switch v := v.(type) {
case string:
return parseDate(v)
default:
return time.Time{}, fmt.Errorf("%T is not a supported as a date", v)
}
}
var timeFormats = []string{
time.RFC1123Z,
time.RFC3339Nano,
time.UnixDate,
time.RubyDate,
time.RFC1123,
time.RFC3339,
time.RFC822,
time.RFC850,
time.RFC822Z,
"2006-01-02",
"2006-01-02 15:04:05",
"2006/01/02",
"2006/01/02 15:04:05",
}
func parseDate(tm string) (t time.Time, err error) {
for _, f := range timeFormats {
if t, err = time.Parse(f, tm); err == nil {
break
}
}
return t, err
}