Number of days in date range, excluding weekends and other dates, in C#

前端 未结 7 1041
别那么骄傲
别那么骄傲 2020-12-15 01:16

I have a C# method like this:

public static int DaysLeft(DateTime startDate, DateTime endDate, Boolean excludeWeekends, String excludeDates)
{
}
相关标签:
7条回答
  • 2020-12-15 01:44

    Here's one example that includes the excluded dates, weekends, and looping. I did change the string excludeDates to a List though. Some null checking should be added.

        public static int DaysLeft(DateTime startDate, DateTime endDate, Boolean excludeWeekends, List<DateTime> excludeDates)
        {
            int count = 0;
            for (DateTime index = startDate; index < endDate; index = index.AddDays(1))
            {
                if (excludeWeekends && index.DayOfWeek != DayOfWeek.Sunday && index.DayOfWeek != DayOfWeek.Saturday)
                {
                    bool excluded = false; ;
                    for (int i = 0; i < excludeDates.Count; i++)
                    {
                        if (index.Date.CompareTo(excludeDates[i].Date) == 0)
                        {
                            excluded = true;
                            break;
                        }
                    }
    
                    if (!excluded)
                    {
                        count++;
                    }
                }
            }
    
            return count;
        }
    

    EDIT: I do want to point out that I would consider this the quick and dirty method - if you didn't have to do this often. If you're performing this a lot and the distance between the startDate and endDate is rather large it would be much better to do the math as stated in one of the other answers. This is suggested in order to get a feel for iterating dates.

    0 讨论(0)
提交回复
热议问题