forked from danott/recurrence
/
day.go
105 lines (84 loc) · 2.22 KB
/
day.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
package recurrence
import (
"encoding/json"
"fmt"
"strconv"
"time"
)
// A Day specifies a day of the month. (1, 2, 3, ...31)
type Day int
// Implement Schedule interface.
func (self Day) IsOccurring(t time.Time) bool {
if self := int(self); self == Last {
return isLastDayInMonth(t)
} else {
return self == t.Day()
}
}
// Implement Schedule interface.
func (self Day) Occurrences(tr TimeRange) chan time.Time {
return occurrencesFor(self, tr)
}
func (self Day) NextAfter(t time.Time) (time.Time, error) {
desiredDay := int(self)
if desiredDay == Last {
if isLastDayInMonth(t) {
return t.AddDate(0, 0, 1).AddDate(0, 1, -1), nil
}
return firstDayOfMonth(t).AddDate(0, 2, -1), nil
}
if t.Day() > desiredDay {
if isLastDayInMonth(t) && desiredDay == First {
return t.AddDate(0, 0, 1), nil
}
return self.NextAfter(t.AddDate(0, 0, 1))
}
if t.Day() < desiredDay {
totalDays := lastDayOfMonth(t).Day()
if totalDays < desiredDay {
return self.NextAfter(t.AddDate(0, 1, 0))
}
return time.Date(t.Year(), t.Month(), desiredDay, 0, 0, 0, 0, t.Location()), nil
}
totalDaysNextMonth := lastDayOfMonth(lastDayOfMonth(t).AddDate(0, 0, 1)).Day()
if totalDaysNextMonth < desiredDay {
return self.NextAfter(t.AddDate(0, 2, -1))
}
return t.AddDate(0, 1, 0), nil
}
// Implement json.Marshaler interface.
func (self Day) MarshalJSON() ([]byte, error) {
if int(self) == Last {
return json.Marshal(map[string]interface{}{"day": "Last"})
} else {
return json.Marshal(map[string]interface{}{"day": int(self)})
}
}
// Implement json.Unmarshaler interface.
func (self *Day) UnmarshalJSON(b []byte) error {
s := string(b)
i, err := strconv.ParseInt(s, 10, 0)
if err != nil {
if s != `"Last"` {
return fmt.Errorf("day cannot unmarshal %s", b)
} else {
*self = Day(Last)
}
} else {
if i < 1 || i > 31 {
return fmt.Errorf("day must be 1-31. Was %#v", i)
} else {
*self = Day(i)
}
}
return nil
}
func isLastDayInMonth(t time.Time) bool {
return t.Month() != t.AddDate(0, 0, 1).Month()
}
func lastDayOfMonth(t time.Time) time.Time {
return firstDayOfMonth(t).AddDate(0, 1, -1)
}
func firstDayOfMonth(t time.Time) time.Time {
return time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location())
}