mercoledì 22 giugno 2011

C# - read range of dates without considering all holidays

The problem
I need to calculate the elapsed days between a date and the other, regardless of public holidays and national holidays.

The idea
The first thing to do was to remove from the range of dates on Saturdays and Sundays, in order to consider only working days.
For national holidays but I thought I'd use a database table containing a list of dates as smalldatetime fields.
But I did not want every year to update all the dates of the table, only to set the new year. So I decided to set any date on the database with a fixed year 2011 (but I could also use more than one year 'recently).
The only date to be updated every year is the Easter holiday because it is considered a date "variable".

This is the table:

My solution
Calculating the difference (in days) between the end date and the start and this would eliminate any other festive dates, according to Saturdays and Sundays and holidays are based on. However, if a holiday falls in one of these two days, obviously the date is eliminated once.

This is the C# code:

public static int GetDateDiff(DateTime start, DateTime end) {

TimeSpan dsDiff = end - start;
int diff = dsDiff.Days;

int diff2 = diff;

if (diff <= 0)
return diff;
using (var ctx = new MyEntities()) {
  //run a cycle on any date, from start to finish
  for(int i = 0; i <= diff2; i++) {
   DateTime dtTemp = start.AddDays(i);
       //a cycle on any holiday date
                 foreach (var t in ctx.T_HOLIDAYS) {
   int yearDiff = - dtTemp.Year;  
   TimeSpan ts = - dtTemp.AddYears(yearDiff);
                        if (ts.Days == 0 && != DayOfWeek.Saturday && != DayOfWeek.Sunday) {
   else if (dtTemp.DayOfWeek == DayOfWeek.Saturday || dtTemp.DayOfWeek == DayOfWeek.Sunday) {
  }//end foreach
 }//end for

Nessun commento:

Posta un commento

Your message will be verified prior to publication. Thanks for your contribution.