planner/item/recur.go

66 lines
995 B
Go
Raw Normal View History

2024-12-01 10:22:47 +01:00
package item
import "time"
type RecurPeriod string
const (
PeriodDay RecurPeriod = "day"
PeriodMonth RecurPeriod = "month"
)
type Recur struct {
Start time.Time
Period RecurPeriod
Count int
}
func (r *Recur) On(date time.Time) bool {
switch r.Period {
case PeriodDay:
return r.onDays(date)
case PeriodMonth:
return r.onMonths(date)
default:
return false
}
}
func (r *Recur) onDays(date time.Time) bool {
if r.Start.After(date) {
return false
}
testDate := r.Start
for {
if testDate.Equal(date) {
return true
}
if testDate.After(date) {
return false
}
dur := time.Duration(r.Count) * 24 * time.Hour
testDate = testDate.Add(dur)
}
}
func (r *Recur) onMonths(date time.Time) bool {
if r.Start.After(date) {
return false
}
tDate := r.Start
for {
if tDate.Equal(date) {
return true
}
if tDate.After(date) {
return false
}
y, m, d := tDate.Date()
tDate = time.Date(y, m+time.Month(r.Count), d, 0, 0, 0, 0, time.UTC)
}
}