In C#, how can I calculate the number of business (or weekdays) days between two dates?
Here's a quick sample code. It's a class method, so will only work inside of your class. If you want it to be static
, change the signature to private static
(or public static
).
private IEnumerable GetWorkingDays(DateTime sd, DateTime ed)
{
for (var d = sd; d <= ed; d = d.AddDays(1))
if (d.DayOfWeek != DayOfWeek.Saturday && d.DayOfWeek != DayOfWeek.Sunday)
yield return d;
}
This method creates a loop variable d
, initializes it to the start day, sd
, then increments by one day each iteration (d = d.AddDays(1)
).
It returns the desired values using yield
, which creates an iterator
. The cool thing about iterators is that they don't hold all of the values of the IEnumerable
in memory, only calling each one sequentially. This means that you can call this method from the dawn of time to now without having to worry about running out of memory.