16,003,243 members
See more:
Hi

I have two calendar controls one for From and the other for To and from the two dates selected i have to calculate the number of days and also i have to exclude the saturdays and sundays (i.e) if i have applied for leave from friday till monday I have to exclude sat and sunday and calculate the leave as 2 how to do it
Posted

## Solution 1

Here You Can Get The Total Number Of Days Between The Two Dates

C#
```DateTime d1=DateTime.MinValue;
DateTime d2=DateTime.MaxValue;
TimeSpan span = d2 - d1;
Console.WriteLine
( "There're {0} days between {1} and {2}" , span.TotalDays, d1.ToString(), d2.ToString() );```

For The Leaves You Have to Write A Separate Routine And Then Subtract It From Total Days.

Then You Will Get The Exact Number Of Days.

Accept The Answer If It Has Helped You
Sergey Alexandrovich Kryukov 1-Mar-12 11:55am
Right, a 5.
--SA

## Solution 3

One can always iterate... if the dates aren't too far apart. This code snippet assumes there are no holidays.
C#
```using System;

{
{
public static long LeaveDays(DateTime from, DateTime to)
{
if (to < from)
{
return LeaveDays(to, from);
}

long days = 0;
DateTime d = from;
while (d <= to)
{
if (d.DayOfWeek != DayOfWeek.Saturday && d.DayOfWeek != DayOfWeek.Sunday)
{
days++;
}
}

return days;
}

}
}```

## Solution 4

Write an extension method to exclude the weekends.

```public static class ExtensionMethods
{
public static int GetNumberOfWorkingDays(this DateTime startDate, DateTime endDate)
{
int numberOfWorkingDays = 0;

for (var nextDate = startDate; nextDate < endDate; nextDate = nextDate.AddDays(1))
{
if (nextDate.DayOfWeek != DayOfWeek.Saturday && nextDate.DayOfWeek != DayOfWeek.Sunday)
{
++numberOfWorkingDays;
}
}

return numberOfWorkingDays;
}
}
```

and then call it from your code, e.g.

C#
```var startDate = DateTime.Now;
var numberDays = startDate.GetNumberOfWorkingDays(endDate);
```