Introduction
In many cases developers have
a demand of calculation and manipulations with business dates.
Scenario:
We want to add “N”
business days/working days to a current date (Or from a specified date). Where
“N” is the number of business days.
Solution:
In this blog I have
described how to add “N” business days/working days to a date
The below C# function
does it all for you. Simply pass in a date, along with the number of
working days you want to add.
public DateTime AddBusinessDays(DateTime DateIn, int Days2Add)
{
DateTime resultDate;
// Adds the N (Days2Add) working days to DateIn (Today)
resultDate = DateIn.AddDays(Days2Add);
// Loops and adds only non-weekend day(working days)
while (resultDate.DayOfWeek == DayOfWeek.Saturday || resultDate.DayOfWeek == DayOfWeek.Sunday)
{
resultDate = resultDate.AddDays((Days2Add < 0 ? -1 : 1));
}
return resultDate;
}
{
DateTime resultDate;
// Adds the N (Days2Add) working days to DateIn (Today)
resultDate = DateIn.AddDays(Days2Add);
// Loops and adds only non-weekend day(working days)
while (resultDate.DayOfWeek == DayOfWeek.Saturday || resultDate.DayOfWeek == DayOfWeek.Sunday)
{
resultDate = resultDate.AddDays((Days2Add < 0 ? -1 : 1));
}
return resultDate;
}
And here's how you call it in your application:
private void button1_Click(object sender, EventArgs e)
{
DateTime newDate = AddBusinessDays(DateTime.Today, 6);
MessageBox.Show("The 6th Business day from today is {0}", newDate.ToString());
}
{
DateTime newDate = AddBusinessDays(DateTime.Today, 6);
MessageBox.Show("The 6th Business day from today is {0}", newDate.ToString());
}
The above code is Tested
No comments:
Post a Comment