Remove Saturdays and Sundays from Calculation

10

I have a project where I work with project activities, my activities have a certain time to complete, but the project has to do the calculation only with administrative days.

For example, an activity starts on 10/26/2015 (Monday) and its duration has 7 days it would have to make the calculation and return to me that the end of the activity would be on 03/11/2015 (Mon, Tue , Fri, Thurs, Fri, Fri and Tues) would have to remove on Saturdays and Sundays.

My project looks like this:

atividade.Inicio = status.InicioPrevisto.Value;
atividade.Duracao = 7;
atividade.Termino = atividade.Inicio.AddDays(duracao);
    
asked by anonymous 25.10.2015 / 19:22

3 answers

8

I found a function ready in OS that seems to solve what you want.

public static DateTime AddBusinessDays(DateTime date, int days) {
    if (days < 0) {
        throw new ArgumentException("days cannot be negative", "days");
    }
    if (days == 0) return date;
    if (date.DayOfWeek == DayOfWeek.Saturday) {
        date = date.AddDays(2);
        days -= 1;
    }
    else if (date.DayOfWeek == DayOfWeek.Sunday) {
        date = date.AddDays(1);
        days -= 1;
    }
    date = date.AddDays(days / 5 * 7);
    int extraDays = days % 5;

    if ((int)date.DayOfWeek + extraDays > 5) {
        extraDays += 2;
    }
    return date.AddDays(extraDays);
}

See running on dotNetFiddle .

Please note that holidays are not considered. But you can adapt for them to be. It is not so simple because of the mobile and regional holidays. But it is doable to set the rules well.

    
25.10.2015 / 19:42
6

There is the NuGet FluentDateTime package that does it very elegantly:

atividade.Inicio = status.InicioPrevisto.Value;
atividade.Duracao = 7;
atividade.Termino = atividade.Inicio.AddBusinessDays(duracao);

AddBusinessDays , as well as AddDays , accepts positive and negative values.

    
26.10.2015 / 13:59
2

Hello, use the GregorianCalendar Class, see the example.

public Boolean Verificadias()
        {
            // Pega o index do dia da semana...
            int IndexDia = (int)System.Globalization.CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(DateTime.Now);
            if (IndexDia > 0 && IndexDia < 6) /// Segunda = 1 a sexta = 5.
            {
                return true;
            }
            else
                return false;
        }

Build a loop that counts the days and adds to your date.

link here

    
26.10.2015 / 12:34