-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdate.go
74 lines (59 loc) · 1.25 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
package asaas
import (
"fmt"
"strings"
"time"
)
type Date time.Time
var dLayout = "2006-01-02"
func (d *Date) UnmarshalJSON(b []byte) error {
s := strings.Trim(string(b), `"`)
if s == "null" || s == `""` {
return nil
}
t, err := time.Parse(dLayout, s)
if err == nil {
*d = Date(t)
}
return nil
}
func (d Date) MarshalJSON() ([]byte, error) {
if d.IsZero() {
return []byte(fmt.Sprintf(`null`)), nil
}
return []byte(fmt.Sprintf(`"%s"`, d.Format())), nil
}
func (d Date) Format() string {
return d.Time().Format(dLayout)
}
func NewDate(year int, month time.Month, day int, loc *time.Location) Date {
return Date(time.Date(year, month, day, 23, 59, 0, 0, loc))
}
func DateNow() Date {
return Date(time.Now())
}
func (d Date) Year() int {
year, _, _, _ := d.date()
return year
}
func (d Date) Month() time.Month {
_, month, _, _ := d.date()
return month
}
func (d Date) Day() int {
_, _, day, _ := d.date()
return day
}
func (d Date) Location() *time.Location {
return d.Time().Location()
}
func (d Date) IsZero() bool {
return d.Time().IsZero()
}
func (d Date) Time() time.Time {
return time.Time(d)
}
func (d Date) date() (year int, month time.Month, day int, yDay int) {
t := d.Time()
return t.Year(), t.Month(), t.Day(), t.YearDay()
}