# Counting Monday and Friday from a Date Range

How can I get Monday and Friday from a date range (start and end date)?

Example:

startdate - 03/24/2014
enddate - 04/01/2014

Result should be:

Monday - 2
Friday - 2

I tried this code:

Monday = CountDays(DayOfWeek.Monday, startDate, endDate);
Friday = CountDays(DayOfWeek.Friday, startDate, endDate);


static int CountDays(DayOfWeek day, DateTime start, DateTime end)
{
TimeSpan ts = end - start;
int count = (int)Math.Floor(ts.TotalDays / 7);
int remainder = (int)(ts.TotalDays % 7);
int sinceLastDay = (int)(end.DayOfWeek - day);
if (sinceLastDay < 0) sinceLastDay += 7;

if (remainder >= sinceLastDay) count++;

return count > 0 ? count : 0;
}


And this code works! Is there any other way to simplify this code?

• I don't understand why you think increasing the time range would somehow increase the processing time. You're not iterating over anything.
– Asad
Mar 28, 2014 at 6:18
• is there any other way that i can simplify that code? or is there any best way that i can do that?
– user1647667
Mar 28, 2014 at 6:19
• Please explain why there should be two Fridays between 2014-03-24 and 2014-04-01? Apr 2, 2014 at 6:43

## 1 Answer

Your code is already good enough.

static int CountDays(DayOfWeek day, DateTime start, DateTime end)
{
start = start.Date.AddDays((7 + day - start.DayOfWeek) % 7);
if (end < start)
return 0;
else
return ((int)(end - start).TotalDays) / 7 + 1;
}

• i think this code look more understandable than my work.
– user1647667
Mar 28, 2014 at 8:38