4
\$\begingroup\$

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?

\$\endgroup\$

migrated from stackoverflow.com Apr 1 '14 at 22:16

This question came from our site for professional and enthusiast programmers.

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

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;
}
\$\endgroup\$
  • \$\begingroup\$ i think this code look more understandable than my work. \$\endgroup\$ – user1647667 Mar 28 '14 at 8:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.