I am resurrecting this post because today I had to find a way to exclude not only Saturday and Sunday, but also holidays. More specifically, I needed to handle various sets of possible holidays, including:
- country-independent holidays (at least for Western countries - for example, January 01).
- calculated holidays (e.g. Easter and Easter Monday).
- Holidays for a specific country (for example, the day of the liberation of Italy or ID4 USA).
- City holidays (for example, the patron saint day of Rome).
- any other custom holiday (for example, "tomorrow our office will be closed").
In the end, I came out with the following set of helper / extension classes: although they don't look clearly elegant because they use inefficient loops widely, they are decent enough to solve my problems forever. I omit all the source code here in this post, hoping it will be useful to someone else as well.
Source
Usage Information
The code is pretty straightforward, however here are a couple of examples to explain how you can use it.
Add 10 business days (skipping only Saturday and Sunday)
var dtResult = DateTimeUtil.AddBusinessDays(srcDate, 10);
Add 10 business days (skipping Saturday, Sunday, and all country-independent holidays for 2019)
var dtResult = DateTimeUtil.AddBusinessDays(srcDate, 10, GetHolidays(2019));
Add 10 business days (skipping Saturday, Sunday, and all Italian holidays for 2019)
var dtResult = DateTimeUtil.AddBusinessDays(srcDate, 10, GetHolidays(2019, "IT"));
Add 10 business days (skipping Saturday, Sunday, all Italian holidays and holidays in Rome in 2019)
var dtResult = DateTimeUtil.AddBusinessDays(srcDate, 10, GetHolidays(2019, "IT", "Rome"));
The above functions and code examples are described in more detail in this post of my blog.