Remove Saturdays and Sundays from Calculation

Asked

Viewed 1,283 times

10

I have a project where I work with activities of a project, my activities have a certain time to be completed, but the project has to make the calculation only with administrative days.

For example an activity starts on 26/10/2015 (Monday) and its duration has 7 days he would have to do the calculation and return me that the end of the activity would be on 03/11/2015 (mon, have, quar, qui, sex, mon and ter) would have to remove Saturdays and Sundays.

My project is like this:

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

3 answers

7


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

using static System.Console;
using System;

public class Program {
    public static void Main()   {
        WriteLine(AddBusinessDays(DateTime.Now, 8));
        WriteLine(AddBusinessDays(new DateTime(2015, 10, 26), 15));
    }

    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);
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Note that holidays are not considered. But it is possible to adapt them to be. It is not so simple because of the mobile and regional holidays. But it is feasible to set the rules well.

5

There is a the Fluentdatetime Nuget package who does it with great elegance:

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

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

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;
        }

Create a loop that counts the days and add on your date..

link here

Browser other questions tagged

You are not signed in. Login or sign up in order to post.