Alan,
I could not reply in the previous post. I don't know why...
Alan,
This is great. How can we get a generalize code? I just gave an example. I want to add "n" days for a given day and the addition has to exclude weekends.
I am very sorry if my explaination was hazy.
Thank you very much for your time and help.
Prasanna.
AlanPosted Sep 28, 2007, 4:49 AM
Hi Prasanna,
This is the most straightforward way of adding any number of business days to a given date (it can also cope with subtraction by adding a negative number of days). It's not very efficient when adding a large number of days (I could supply a more efficient method if you need it) but, for most practical purposes, it will still be quick enough:
using System;
class Program
{
static void Main()
{
string startDate1 = "09/24/2007 10:00:00";
int increment1 = 5;
string endDate1 = AddBusinessDays(startDate1, increment1);
Console.WriteLine("{0} plus {1} business days is {2}", startDate1, increment1, endDate1);
string startDate2 = "09/28/2007 10:00:00";
int increment2 = 4;
string endDate2 = AddBusinessDays(startDate2, increment2);
Console.WriteLine("{0} plus {1} business days is {2}", startDate2, increment2, endDate2);
Console.ReadKey();
}
public static string AddBusinessDays(string startDate, int numDays)
{
string format = "MM/dd/yyyy HH:mm:ss";
DateTime dt = DateTime.ParseExact(startDate, format, null);
if (numDays == 0) return startDate;
if (numDays > 0)
{
for (int count = 1; count <= numDays; count++)
{
dt = dt.AddDays(1);
if (dt.DayOfWeek == DayOfWeek.Saturday)
dt = dt.AddDays(2);
else if (dt.DayOfWeek == DayOfWeek.Sunday)
dt = dt.AddDays(1);
}
}
else
{
for (int count = 1; count <= -numDays; count++)
{
dt = dt.AddDays(-1);
if (dt.DayOfWeek == DayOfWeek.Saturday)
dt = dt.AddDays(-1);
else if (dt.DayOfWeek == DayOfWeek.Sunday)
dt = dt.AddDays(-2);
}
}
return dt.ToString(format);
}
}