Site icon Ryadel

ASP.NET C# DateTime helper functions to add, subtract, calculate and get Business Days

Classe ASP.NET C# per il controllo e il calcolo formale del Codice Fiscale

Today I had to find a way to perform some rather "uncommon" DateTime-based operations: to be more specific, I needed to check if a date object resulting from a user input was at least two business days ahead of the current day.

I initially thought that excluding the Saturday and Sunday weekdays would have been enough, however I soon realized that I had underestimated the problem: I halso had to put the holidays into the loop. As if it wasn't enough, I also had to consider the fact that each country - and even each town, if we consider the italian's patron days - has their own holidays. Therefore, I had to find a way to programmatically handle various sets of possible holidays, such as:

  • country-invariant holidays (at least for the Western countries - such as January, 01)
  • calculated holidays (such as Easter and Easter monday).
  • country-specific holidays (such as the Italian liberation day or the United States ID4).
  • town-specific holidays (such as the Rome St. Patron Day).
  • any other custom-made holiday (such as "tomorrow our office wil be closed").

Eventually, I came out with the following set of helper/extensions classes: although they aren't blatantly elegant, as they do make a massive use of unefficient loops, they are decent enough to solve these kind of issues for good. I'm dropping the whole source code here in this post, hoping it will be useful to someone else as well.

Source Code

Here's the source code: notice that main methods (AddBusinessDays, SubtractBusinessDays and GetBusinessDays) can be either used as static helper methods or extension methods.

Usage info

The code is quite self-explanatory, however here's a couple examples to explain how you can use it.

Add 10 business days (skipping only saturday and sunday week days)

Add 10 business days (skipping saturday, sunday and all country-invariant holidays for 2019)

Add 10 business days (skipping saturday, sunday and all italian holidays for 2019)

Add 10 business days (skipping saturday, sunday, all italian holidays and the Rome-specific holidays for 2019)

Conclusion

That's pretty much it: if you like the source code and/or if you need additional info, feel free to comment. Happy coding!

 

Exit mobile version