I am trying to add hours to a date but want the new date to exclude weekends and only be between 9.00 to 17.00.
example:
first scenario:
if my date is 23/02/2012 16:00:00.
if I add 4 hours to that my new date should be 24/02/2012 12:00:00 (which will be within working hours)
second scenario:
if my date is 24/02/2012 09:00:00 (which is a friday)
if I add 24 hours then the new date should be 27/02/2012 09:00:00 (which would be monday next week at 9am)
so far I got this but am stuck as this will not count for any date that is in past say date passed was 10/02/2012(Friday last week) :
private static void ExcludeWeekend(Datetime dt)
{
DateTime todaysDate = DateTime.Today;
DateTime dueDate = null;
if (dueDate.DayOfWeek == DayOfWeek.Friday)
{
dueDate.AddHours(48);
}
else if (dueDate.DayOfWeek == DayOfWeek.Saturday)
{
dueDate.AddHours(72);
}
}
You can use the class CalendarDateAdd from the Time Period Library for .NET:
// ----------------------------------------------------------------------
public void CalendarDateAddSample()
{
CalendarDateAdd calendarDateAdd = new CalendarDateAdd();
// use only weekdays
calendarDateAdd.AddWorkingWeekDays();
// setup working hours
calendarDateAdd.WorkingHours.Add( new HourRange( new Time( 09 ), new Time( 17 ) ) );
DateTime start = new DateTime( 2012, 2, 23 ); // start date
TimeSpan offset = new TimeSpan( 4, 0, 0 ); // 4 hours
DateTime? end = calendarDateAdd.Add( start, offset ); // end date
Console.WriteLine( "start: {0}", start );
Console.WriteLine( "offset: {0}", offset );
Console.WriteLine( "end: {0}", end );
} // CalendarDateAddSample