Skip to content

Commit

Permalink
Merge pull request #82 from swizzley/master
Browse files Browse the repository at this point in the history
Count Holidays in range
  • Loading branch information
rickar authored Dec 18, 2021
2 parents 90b7ddf + c47e868 commit 47cabcb
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
19 changes: 19 additions & 0 deletions v2/cal_business.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,25 @@ func (c *BusinessCalendar) WorkdaysInMonth(year int, month time.Month) int {
return c.WorkdaysRemain(t)
}

// HolidaysInRange reports the number of holidays between the start and end
// times (inclusive).
func (c *BusinessCalendar) HolidaysInRange(start, end time.Time) int {
factor := 1
if end.Before(start) {
factor = -1
start, end = end, start
}
result := 0
to := DayStart(end)
for i := DayStart(start); i.Before(to) || i.Equal(to); i = i.AddDate(0, 0, 1) {
_, holiday, _ := c.IsHoliday(i)
if holiday {
result++
}
}
return factor * result
}

// WorkdaysInRange reports the number of workdays between the start and end
// times (inclusive).
func (c *BusinessCalendar) WorkdaysInRange(start, end time.Time) int {
Expand Down
37 changes: 37 additions & 0 deletions v2/cal_business_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,43 @@ func TestWorkdaysInRange(t *testing.T) {
}
}

func TestHolidaysInRange(t *testing.T) {
c := NewBusinessCalendar()
hol := &Holiday{
Type: ObservancePublic,
Month: time.July,
Day: 4,
Observed: []AltDay{
{Day: time.Saturday, Offset: -1},
{Day: time.Sunday, Offset: 1},
},
Func: CalcDayOfMonth,
}
c.AddHoliday(hol)

tests := []struct {
f time.Time
t time.Time
want int
}{
{d(2015, 4, 4), d(2015, 4, 5), 0},
{d(2015, 7, 1), d(2015, 7, 6), 1},
}

for _, test := range tests {
got := c.HolidaysInRange(test.f, test.t)
if got != test.want {
t.Errorf("got: %d; want: %d (%s-%s)", got, test.want, test.f, test.t)
}
if !test.f.Equal(test.t) {
got = c.HolidaysInRange(test.t, test.f)
if got != -test.want {
t.Errorf("got: %d; want: %d (%s-%s)", got, -test.want, test.t, test.f)
}
}
}
}

func TestWorkdayN(t *testing.T) {
c := NewBusinessCalendar()
hol := &Holiday{
Expand Down

0 comments on commit 47cabcb

Please sign in to comment.