Count number of Mondays in a given date range

ThePeeje picture ThePeeje · Oct 29, 2008 · Viewed 32.1k times · Source

Given a date range, I need to know how many Mondays (or Tuesdays, Wednesdays, etc) are in that range.

I am currently working in C#.

Answer

Jon B picture Jon B · Oct 29, 2008

Try this:

static int CountDays(DayOfWeek day, DateTime start, DateTime end)
{
    TimeSpan ts = end - start;                       // Total duration
    int count = (int)Math.Floor(ts.TotalDays / 7);   // Number of whole weeks
    int remainder = (int)(ts.TotalDays % 7);         // Number of remaining days
    int sinceLastDay = (int)(end.DayOfWeek - day);   // Number of days since last [day]
    if (sinceLastDay < 0) sinceLastDay += 7;         // Adjust for negative days since last [day]

    // If the days in excess of an even week are greater than or equal to the number days since the last [day], then count this one, too.
    if (remainder >= sinceLastDay) count++;          

    return count;
}