This repository has been archived by the owner on Dec 3, 2020. It is now read-only.
/
month.go
95 lines (82 loc) · 1.92 KB
/
month.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
package recurrence
import (
"encoding/json"
"fmt"
"time"
)
// A Month represents a month of the year. Just like time.Month.
type Month time.Month
// The months of the year
const (
January Month = 1 + iota
February
March
April
May
June
July
August
September
October
November
December
)
// String implements the Stringer interface.
func (m Month) String() string {
return time.Month(m).String()
}
// IsOccurring implements the Schedule interface.
func (m Month) IsOccurring(t time.Time) bool {
return t.Month() == time.Month(m)
}
// Occurrences implements the Schedule interface.
func (m Month) Occurrences(tr TimeRange) chan time.Time {
return occurrencesFor(m, tr)
}
func (m Month) nextAfter(t time.Time) (time.Time, error) {
desiredMonth := int(m)
tMonth := int(t.Month())
if tMonth < desiredMonth {
return time.Date(t.Year(), time.Month(desiredMonth), 1, 0, 0, 0, 0, time.UTC), nil
}
if tMonth > desiredMonth || (tMonth == desiredMonth && isLastDayInMonth(t)) {
return time.Date(t.Year()+1, time.Month(desiredMonth), 1, 0, 0, 0, 0, time.UTC), nil
}
return t.AddDate(0, 0, 1), nil
}
// MarshalJSON implements the json.Marshaler interface.
func (m Month) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]interface{}{"month": time.Month(m).String()})
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (m *Month) UnmarshalJSON(b []byte) error {
switch string(b) {
case `1`, `"January"`:
*m = January
case `2`, `"February"`:
*m = February
case `3`, `"March"`:
*m = March
case `4`, `"April"`:
*m = April
case `5`, `"May"`:
*m = May
case `6`, `"June"`:
*m = June
case `7`, `"July"`:
*m = July
case `8`, `"August"`:
*m = August
case `9`, `"September"`:
*m = September
case `10`, `"October"`:
*m = October
case `11`, `"November"`:
*m = November
case `12`, `"December"`:
*m = December
default:
return fmt.Errorf("Weekday cannot unmarshal %s", b)
}
return nil
}