-
Notifications
You must be signed in to change notification settings - Fork 3
/
date.go
executable file
·90 lines (72 loc) · 1.94 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
88
89
90
// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.
package types
import (
"encoding/json"
"fmt"
"strings"
"time"
)
// Date is a wrapper around time.Time that allows for JSON marshaling a date string formatted as "2006-01-02".
type Date struct {
time.Time
}
var (
_ json.Marshaler = &Date{}
_ json.Unmarshaler = &Date{}
_ fmt.Stringer = &Date{}
)
// NewDate returns an instance of Date from a time.Time.
func NewDate(t time.Time) *Date {
d := DateFromTime(t)
return &d
}
// DateFromTime returns a Date from a time.Time.
func DateFromTime(t time.Time) Date {
return Date{t}
}
// NewDateFromString returns an instance of Date from a string formatted as "2006-01-02".
func NewDateFromString(str string) (*Date, error) {
d, err := DateFromString(str)
if err != nil {
return nil, err
}
return &d, nil
}
// DateFromString returns a Date from a string formatted as "2006-01-02".
func DateFromString(str string) (Date, error) {
var d Date
var err error
d.Time, err = time.Parse("2006-01-02", str)
return d, err
}
// MustNewDateFromString returns an instance of Date from a string formatted as "2006-01-02" or panics.
// Avoid using this function in production code.
func MustNewDateFromString(str string) *Date {
d := MustDateFromString(str)
return &d
}
// MustDateFromString returns a Date from a string formatted as "2006-01-02" or panics.
// Avoid using this function in production code.
func MustDateFromString(str string) Date {
d, err := DateFromString(str)
if err != nil {
panic(err)
}
return d
}
func (d Date) GetTime() time.Time {
return d.Time
}
func (d Date) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, d.Time.Format("2006-01-02"))), nil
}
func (d *Date) UnmarshalJSON(data []byte) error {
var err error
str := string(data)
str = strings.Trim(str, `"`)
d.Time, err = time.Parse("2006-01-02", str)
return err
}
func (d Date) String() string {
return d.Time.Format("2006-01-02")
}