github.com/martinohmann/rfoutlet@v1.2.1-0.20220707195255-8a66aa411105/internal/schedule/interval.go (about)

     1  package schedule
     2  
     3  import "time"
     4  
     5  // Interval defines a time frame consisting of a start and end time and a list
     6  // of weekdays for which the interval is valid.
     7  type Interval struct {
     8  	ID       string         `json:"id"`
     9  	Enabled  bool           `json:"enabled"`
    10  	Weekdays []time.Weekday `json:"weekdays"`
    11  	From     DayTime        `json:"from"`
    12  	To       DayTime        `json:"to"`
    13  }
    14  
    15  // Contains returns true if interval is enabled and t lies within.
    16  func (i Interval) Contains(t time.Time) bool {
    17  	if !i.Enabled || !i.enabledOn(t.Weekday()) {
    18  		return false
    19  	}
    20  
    21  	dt := NewDayTime(t.Hour(), t.Minute())
    22  
    23  	if i.From.After(i.To) {
    24  		return !dt.Between(i.To, i.From)
    25  	}
    26  
    27  	return dt.Between(i.From, i.To)
    28  }
    29  
    30  func (i Interval) enabledOn(weekday time.Weekday) bool {
    31  	for _, wd := range i.Weekdays {
    32  		if wd == weekday {
    33  			return true
    34  		}
    35  	}
    36  
    37  	return false
    38  }