fix overflow bug with adding months

This commit is contained in:
Erik Winter 2021-03-03 11:54:36 +01:00
parent ee1aad104b
commit 5931868b62
3 changed files with 18 additions and 3 deletions

View File

@ -53,7 +53,7 @@ type Date struct {
func NewDate(year, month, day int) Date { func NewDate(year, month, day int) Date {
if year == 0 && month == 0 && day == 0 { if year == 0 || month == 0 || month > 12 || day == 0 {
return Date{} return Date{}
} }
@ -209,6 +209,14 @@ func (d Date) Add(days int) Date {
return NewDate(year, int(month), day+days) return NewDate(year, int(month), day+days)
} }
func (d Date) AddMonths(addMonths int) Date {
year, month, day := d.t.Date()
addYears := int((int(month) + addMonths) / 12)
newMonth := (int(month) + addMonths) % 12
return NewDate(year+addYears, newMonth, day)
}
func (d Date) Equal(ud Date) bool { func (d Date) Equal(ud Date) bool {
return d.t.Equal(ud.Time()) return d.t.Equal(ud.Time())
} }

View File

@ -268,8 +268,7 @@ func (enm EveryNMonths) RecursOn(date Date) bool {
if tDate.After(date) { if tDate.After(date) {
return false return false
} }
tYear, tMonth, tDay := tDate.Time().Date() tDate = tDate.AddMonths(enm.N)
tDate = NewDate(tYear, int(tMonth)+enm.N, tDay)
} }
} }

View File

@ -359,4 +359,12 @@ func TestEveryNMonths(t *testing.T) {
}) })
} }
}) })
t.Run("recurs every year", func(t *testing.T) {
recur := task.EveryNMonths{
Start: task.NewDate(2021, 3, 1),
N: 12,
}
test.Equals(t, false, recur.RecursOn(task.NewDate(2021, 3, 9)))
})
} }