Sumar fechas sin tomar en cuenta fines de semana

by eva02lasthope 10. junio 2009 12:49

Sumar fechas sin tomar en cuenta fines de semana


Una compañerita de trabajo me pidió un favor el cual consistía en poder sumarle a una fecha N días pero sin tomar en cuenta los fines de semana. Las siguientes funciones hacen dicha tarea:

  • DateTimeIgnoringWeekEnds: La cual recibe como parametros la fecha inicial y los días a sumar.
  • NumberOfWeekEndDays: Esta función es usada por la función anterior y nos ayuda a saber cuantos días son sabado o domingo entre dos fechas.

    Ejemplo :

using System;
/// 
/// Summary description for Class1
/// 
public class Class1
{
    public Class1()
    {
        //Ejemplo donde queremos 13 días
        DateTime dtmFechInicio = DateTime.Now;
        DateTime dtmFechaFinal = DateTimeIgnoringWeekEnds(dtmFechInicio, 13);
    }
 
    public DateTime DateTimeIgnoringWeekEnds(DateTime starDate, int days)
    {
        int intweekends = 0;
        int intHelp = 0;
 
        DateTime endDate = starDate.AddDays(days);
 
        do
        {
            intweekends = NumberOfWeekEndDays(starDate, endDate);
            endDate = starDate.AddDays(days + intweekends);
 
            if (intHelp == 0 || intHelp != intweekends)
                intHelp = intweekends;
            else
                intweekends = 0;
 
        } while (intweekends != 0);
        return endDate;
    }
 
    private int NumberOfWeekEndDays(DateTime startDate, DateTime endDate)
    {
        int intContador = 0;
        DateTime tempDate = startDate;
        while (tempDate <= endDate)
        {
            if (tempDate.DayOfWeek == DayOfWeek.Saturday ||
              tempDate.DayOfWeek == DayOfWeek.Sunday)
            {
                intContador++;
            }
            tempDate = tempDate.AddDays(1);
        }
        return intContador;
    }
}

Tags: ,

dotNet

Agregar Comentario


(Su Gravatar icono será mostrado)

  Country flag

biuquote
  • Comentario
  • Vista Previa
Loading



Disclaimer
Las opiniones mostradas en este blog son responsabilidad del autor y sólo son con la finalidad de compartir conocimientos a la comunidad de tecnologías de información.

© Copyright 2010 Mindev