Introduction
I needed a generic solution to resolve our international delivery needs and as we are working on business days, we needed a way to take this into account. Inheriting from the DateTime
class seemed the first port of call, but the DateTime
class is sealed. So the best solution was to use an extension method to get around this problem (only available in C# 3.0 onwards?). This is a simple solution that only includes Saturday and Sunday as "holiday" days... please feel free to extend this further to include your countries national holidays/bank holidays, etc. My inspiration for this was from the following CodeProject article which I found by Googling: Business Dates C#.
US Holiday Days Web Service
There is actually a Web service available that exposes US holiday days but we (my company) are going to implement a different solution embedded within our existing architecture.
Using the Code
Dead easy! Put this wherever you like and it will extend the DateTime
class (System.DateTime
) to add the following method - AddBusinessDays(int days)
:
public static class DateTimeExtensions
{
public static DateTime AddBusinessDays(this DateTime date, int days)
{
double sign = Convert.ToDouble(Math.Sign(days));
int unsignedDays = Math.Sign(days) * days;
for (int i = 0; i < unsignedDays; i++)
{
do
{
date = date.AddDays(sign);
}
while (date.DayOfWeek == DayOfWeek.Saturday ||
date.DayOfWeek == DayOfWeek.Sunday);
}
return date;
}
}
The extension method works in exactly the same way as the standard AddDays
method.
If you came here to learn about extension methods, then you can see how ridiculously easy it is. Simply define a static
class and call it whatever you like, then include a static
method that contains this
as the first parameter, i.e. DoWhateverYouWant(this type ref)
so if you want to write an extension method for the DataTable
class you could simply do:
public static void DoWhateverYouWant(this DataTable myDataTable) { ... }
My intention was not to teach about extension methods - if this is your bag, then check out this article.
Extending the Extension Method (Don't You Just Love .NET)
Like I said, please feel free to extend this to include national holidays, localization and whatever else you can come up with!
History
- 10th August, 2007: Initial post