-2

I am developing c#.net solution where i have to calculate End Date from start date in date time picker based on provided duration date.(excluding weekends)

i.e.

Start Date: 02/09/2015 days: 5

Start Date = 02/09/2015 + 5 days (Excludes weekends)

End Date = 08/09/2015

thanks you,

NASSER
  • 5,900
  • 7
  • 38
  • 57
soon keong
  • 23
  • 2

2 Answers2

1

Try this,

var startDate = DateTime.Now;  // Put your actual start date here
for (int i = 0; i < 5;)        // Put number of days to add instead of 5
{
    startDate = startDate.AddDays(1);
    if (startDate.DayOfWeek == DayOfWeek.Saturday || startDate.DayOfWeek == DayOfWeek.Sunday)
    {              
        continue;
    }
    i++;
}
var finalDate = startDate;

enter image description here

NASSER
  • 5,900
  • 7
  • 38
  • 57
1

Assuming your start date is a weekday, just add 7 days to it. The calculation for an arbitrary number of days would be as follows:

DateTime StartDate = new DateTime(2015, 9, 2);
DateTime EndDate = StartDate.AddDays(duration/5*7+duration%5);

Assuming we have an array of businessHolidays, we could account for those as well:

for( var index = 0; index < businessHolidays.length; index++) {
   var holiday = businessHolidays[index];
   if (holiday.Date >= StartDate.Date && holiday.Date <= EndDate.Date) {
      EndDate.AddDays(1);
   }
}

Finally, we check the resulting date to see if it falls on a weekend. This is necessary if the start date was a weekend or we pushed the date due to a holiday.

if ( EndDate.DayOfWeek == DayOfWeek.Saturday ) {
    EndDate.AddDays(2);
} else if ( EndDate.DayOfWeek == DayOfWeek.Sunday ) {
    EndDate.AddDays(1);
}
B2K
  • 2,541
  • 1
  • 22
  • 34