65.9K
CodeProject is changing. Read more.
Home

Find the count of a weekday between two dates without iterating/looping

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Nov 15, 2011

CPOL
viewsIcon

4840

I like things simple for debugging purposes... LINQ implies a list or some iterable thing, but that's just me. I think this works:static int CountDayOcurrence(DateTime start, DateTime end, DayOfWeek day){ var wstart = start.AddDays(7 - (int) start.DayOfWeek); // Sunday after start...

I like things simple for debugging purposes... LINQ implies a list or some iterable thing, but that's just me. I think this works:

static int CountDayOcurrence(DateTime start, DateTime end, DayOfWeek day)
{
    var wstart = start.AddDays(7 - (int) start.DayOfWeek);  // Sunday after start date
    var wend = end.AddDays(-(int)end.DayOfWeek);            // Sunday before end

    var ocurrences = (wend - wstart).Days / 7;              // complete weeks (Sunday through Sunday)

    if (start.DayOfWeek <= day)                          //
        ocurrences++;

    if (end.DayOfWeek >= day)
        ocurrences++;

    return ocurrences;
}