3

I have my start date as 05/03/2012 and duration is 200 days now I would like to get the end date excluding sundays. So that my end date should be 05/02/2013.. Can some one help me

Vivekh
  • 4,141
  • 11
  • 57
  • 102

2 Answers2

1

Try this for me:

var startDate = new DateTime(2012, 5, 3);
var sundaysOverDuration = 200 / 7;
var actualDuration = 200 + sundaysOverDuration;
var newDate = startDate.AddDays(actualDuration);

I also honestly have to admit that this link is flat out elegant surrounding how it handles a lot of the exceptions that exist when doing these types of calculations. I'm not sure you need something that complex, but it's worth letting you know. I'm going to inline the code just to ensure it's preserved if the link is ever broken.

public static double GetBusinessDays(DateTime startD, DateTime endD) 
{
    double calcBusinessDays =
        1 + ((endD-startD).TotalDays * 6 -
        (startD.DayOfWeek-endD.DayOfWeek) * 2) / 7;
    if ((int)startD.DayOfWeek == 0) calcBusinessDays --;
    return calcBusinessDays;
}

public static DateTime AddWorkDaysToStartDate(DateTime startD, double businessDays)
{
    int DoW = (int)startD.DayOfWeek;
    double temp = businessDays + DoW + 1;
    if (DoW != 0) temp --;
    DateTime calcendD = startD.AddDays(
    Math.Floor(temp / 6)*2-DoW + temp
        - 2* Convert.ToInt32(temp % 6 == 0)) ;
}

Finally, based on your question it doesn't appear you need to handle holidays, but if you do the solution is much more complex and would need to be database driven, so just keep that in mind.

Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232
  • Counterexample - start date of (2012, 9, 18) and add six days. – Ian Nelson Sep 18 '12 at 11:04
  • @IanNelson, yes this would break with a number that low. However, I did add a more elegant solution for the OP if one is needed. – Mike Perrenoud Sep 18 '12 at 11:10
  • @Vivekh, no the example is built for a five day work week, but all you **should** need to do is change a few of the assumptions and you're setup for a six day work week. Let me modify it a tad and then you can see if it works for you. – Mike Perrenoud Sep 18 '12 at 11:27
  • @Vivekh, I modified some of the assumptions, but I'm not in a position to test the modifications so there may be errors in them. – Mike Perrenoud Sep 18 '12 at 11:29
0

You can use the CalendarDateAdd class from the Time Period Library for .NET:

// ----------------------------------------------------------------------
public void AddDaysSample()
{
    CalendarDateAdd calendarDateAdd = new CalendarDateAdd();
    calendarDateAdd.AddWorkingWeekDays();
    calendarDateAdd.WeekDays.Add( DayOfWeek.Saturday );

    DateTime start = new DateTime( 2012, 5, 3 );
    TimeSpan duration = new TimeSpan( 200, 0, 0, 0 );
    DateTime? end = calendarDateAdd.Add( start, duration );
    Console.WriteLine( "AddDaysSample : {0:d} + {1} days = {2:d}", start, duration.Days, end );
} // AddDaysSample