user650922
user650922

Reputation: 2111

Calculating the number of holidays between a date range in C#

I would like to know how to calculate the number of holidays between a date range in C#.

Example :Date Range 1st jan 2012 to 1st Feb 2012

 conditions:
    holiday1=>From Date (30th Dec 2011 to 2nd jan 2012)
    holiday2 =>From Date(16th jan 2012 to 18 th jan 2012)
    holiday3=>From Date(30the jan 2012 to 2nd Feb 2012)

Here as first holidays is till 2nd jan I need to calculate 2 days for holiday1 as well as 2 days for holidays 3 and for holidays 2nd that's not a problem for me to calculate.

Upvotes: 0

Views: 1288

Answers (1)

jason
jason

Reputation: 241651

First, you need a single, consistent definition of holiday. There are many. There is the U.S. Federal Government definition, there is the NYSE definition, and even some states have their own holidays (e.g., Patriot's Day in Massachusetts). And, of course, I've neglected the fact that the U.S. isn't the only country in the world. So, let's say that you have formulated this definition, and you've codified into a method:

bool IsHoliday(this DateTime date) { // }

Now you can say:

int CountHolidaysBetween(DateTime start, DateTime end) {
    int days = end.Day.Substract(start.Day).Days;
    return Enumerable.Range(0, days + 1)
                     .Select(day => start.Day.AddDays(day))
                     .Count(d => d.IsHoliday());
}

or, if you think that's too fancy:

int CountHolidaysBetween(DateTime start, DateTime end) {
    DateTime current = start.Day;
    int count = 0;
    while(current <= end.Day) {
        if(current.IsHoliday()) { count++; }
        current = current.AddDays(1);
    }
    return count;
}

As you can see, the most important part is deciding upon your definition of holiday and codifying it into a method. That's not something we can decide for you. We don't know if you're in the U.S., we don't know if you're a government agency, we don't know if you have to observe state-specific holidays, etc.

Upvotes: 4

Related Questions