Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

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

0.00/5 (No votes)
17 Nov 2011CPOL 4.8K  
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:


C#
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;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)