Home » excel » vb.net – Is there a .NET method equivalent to NETWORKDAYS in Excel?

vb.net – Is there a .NET method equivalent to NETWORKDAYS in Excel?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m trying to do some date math in Visual Basic. The NETWORKDAYS function in Excel is exactly what I need. Is there an equivalent or similar method available in .NET?

How to&Answers:

Take a look at this:

private int CountWorkDays( DateTime startDate, DateTime endDate, List<DateTime> excludedDates )
{
    int dayCount = 0;
    int inc = 1;
    bool endDateIsInPast = startDate > endDate;
    DateTime tmpDate = startDate;
    DateTime finiDate = endDate;

    if( endDateIsInPast )
    {
        // Swap dates around
        tmpDate = endDate;
        finiDate = startDate;

        // Set increment value to -1, so it DayCount decrements rather 
        // than increments
        inc = -1;
    }

    while( tmpDate <= finiDate )
    {
        if( !excludedDates.Contains( tmpDate ) )
        {
            dayCount += inc;
        }

        // Move onto next day
        tmpDate = tmpDate.AddDays( 1 );
    }

    return dayCount;
}

Answer:

Here you will have two articles as a good starting point:

Optimized Calculation Algorithm for Business Days

and

Business Dates Calculation

Answer:

Not as far as I know, but it won’t be too hard to come up with one.

Assuming Saturday and Sunday are off, you calculate the number of days in the month, iterate through the dates, subtract the number of days in the month if current date is Sunday or Saturday or it matches the value in the holidays array.