1

Developing in c#.I have two DateTime objects. I have to eliminate the Saturday and Sunday from the days count. Lets suppose I have 5 daysincluding Saturday and Sunday. I want to check the days for Saturday Sunday and reduces the days count.

 DateTime startDate = DateTime.ParseExact(startDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
 DateTime endDate = DateTime.ParseExact(endDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
 TimeSpan diff = endDate - startDate;
 days = diff.Days;

I have tried this,

How can I calculate the Number of Weekends between two dates

but i am unable to eliminate saturday sunday as the given link only eliminate the weekends if the dates difference is greater than 7. Haven't got my solution yet.

Rand Random
  • 7,300
  • 10
  • 40
  • 88
Farrukh Sarmad
  • 315
  • 2
  • 5
  • 24

2 Answers2

4

How about a simple loop between the days of the two dates and using DayOfWeek for checking if the day is a Saturday or Sunday?

Something like below should work:

int weekendDays = 0;

for(DateTime date = startDate; date.Date <= endDate.Date; date = date.AddDays(1))
{
    if ((date.DayOfWeek == DayOfWeek.Saturday) || (date.DayOfWeek == DayOfWeek.Sunday))
    {
        weekendDays++;
    }
}
Adrian
  • 8,271
  • 2
  • 26
  • 43
0

You cold use the following:

int daycount = 0;
while (startDate < endDate) 
{
    startDate = startDate.AddDays(1);
    int DayNumInWeek = (int)startDate.DayOfWeek;
    if (DayNumInWeek != 0 && DayNumInWeek != 6)
         daycount += 1;       
}

Check This link or This link for more info and options.

Also duplicate of Calculate the number of business days between two dates? , which has a nice LINQ approach by Alpha

To get a better performance and readability, you could implement that.

Bruno Miquelin
  • 651
  • 1
  • 8
  • 22