Click here to Skip to main content
15,881,380 members
Articles / Web Development / ASP.NET
Alternative
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
17 Nov 2011CPOL 4.7K  
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)


Written By
Team Leader Formulatrix
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --