Find next 5 working days starting from today

The order is important. The AddDays should be called first, and after it is called we check if the new day matches our criteria.

Note: I have renamed the i variable so it is more clear.

DateTime date1 = new DateTime(2019, 12, 23); 
int daysAdded = 0;

while (daysAdded < 5)
{
    date1 = date1.AddDays(1);
    if (!DateSystem.IsPublicHoliday(date1, CountryCode.IT) && !DateSystem.IsWeekend(date1, CountryCode.IT)) {
        // We only consider laboral days
        // laboral days: They are not holidays and are not weekends
        daysAdded ++;
    }
}

I always try to generalize my solutions, so here's one enabling LINQ:

public bool IsWorkingDay(DateTime dt)
    => !DateSystem.IsPublicHoliday(dt) && !DateSystem.IsWeekend(dt);

public DateTime NextWorkingDay(DateTime dt)
{
    dt = dt.AddDays(1);
    while (!IsWorkingDay(dt))
        dt = dt.AddDays(1);
    return dt;
}

public IEnumerable<DateTime> WorkingDaysFrom(DateTime dt)
{
    if (!IsWorkingDay(dt))
        dt = NextWorkingDay(dt); // includes initial dt, remove if unwanted
    while (true)
    {
        yield return dt;
        dt = NextWorkingDay(dt);
    }
}

This will pump out working days from a given date until end of time, and then use LINQ to grab the number you want:

var next5 = WorkingDaysFrom(DateTime.Today).Take(5).ToList();

here's how to get all the working days in 2020:

var working2020 = WorkingDaysFrom(new DateTime(2020, 1, 1))
    .TakeWhile(dt => dt.Year == 2020)
    .ToList();

Tags:

C#

Date