Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of Mondays in a given date range

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#.

like image 692
ThePeeje Avatar asked Sep 10 '25 02:09

ThePeeje


1 Answers

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

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!