-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
date.go
115 lines (100 loc) · 1.93 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package main
import (
"time"
)
type Day string
const (
Sun Day = "Sun"
Mon Day = "Mon"
Tue Day = "Tue"
Wed Day = "Wed"
Thu Day = "Thu"
Fri Day = "Fri"
Sat Day = "Sat"
)
func (d Day) Valid() bool {
switch d {
case Sun, Mon, Tue, Wed, Thu, Fri, Sat:
return true
default:
return false
}
}
func (d Day) ToWeekday() time.Weekday {
switch d {
case Sun:
return time.Sunday
case Mon:
return time.Monday
case Tue:
return time.Tuesday
case Wed:
return time.Wednesday
case Thu:
return time.Thursday
case Fri:
return time.Friday
case Sat:
return time.Saturday
default:
panic("never happen")
}
}
var tz *time.Location
func init() {
tz, _ = time.LoadLocation("Asia/Tokyo") // TODO: Catch error gracefully
}
type Date struct {
Time time.Time
}
func (d Date) Day() Day {
switch d.Time.Weekday() {
case time.Sunday:
return Sun
case time.Monday:
return Mon
case time.Tuesday:
return Tue
case time.Wednesday:
return Wed
case time.Thursday:
return Thu
case time.Friday:
return Fri
case time.Saturday:
return Sat
default:
panic("never happen")
}
}
func (d Date) In(start, end Date) bool {
return !d.Time.Before(start.Time) && !d.Time.After(end.Time)
}
func (d Date) Next(day Day) Date {
wd := day.ToWeekday()
for i := 0; i < 7; i++ {
t := d.Time.Add(time.Duration(i*24) * time.Hour)
if t.Weekday() == wd {
return Date{Time: t}
}
}
panic("never happen")
}
func (d Date) NextDay() Date {
return Date{Time: d.Time.Add(24 * time.Hour)}
}
func (d Date) ToTime(hour, minute int) time.Time {
return d.Time.Add(time.Duration(hour)*time.Hour + time.Duration(minute)*time.Minute)
}
func (d Date) MarshalJSON() ([]byte, error) {
s := d.Time.Format(`"2006-01-02T00:00:00.000Z"`)
return []byte(s), nil
}
func (d *Date) UnmarshalJSON(data []byte) error {
if string(data) == "null" {
return nil
}
var err error
d.Time, err = time.ParseInLocation(`"2006-01-02T00:00:00.000Z"`, string(data), tz)
return err
}