Reader Level:
ARTICLE

Difference between two dates

Posted by Arunava Bhattacharjee Articles | Learn .NET May 25, 2010
Exclude weekends and holidays from a date duration.
  • 0
  • 0
  • 18048

HTML clipboard

Problem:  In projects sometimes it is needed to find the difference between two dates for many important calculations. For example, in typical production support system we need to calculate the SLA( Service Level Agreement) for each people who are assigned a task. It can be project level, account level or individual level. To calculate the SLA timeframe we need to find when the task or ticket has been raised (Start time) and when it is closed (End Time). Now the problem is if a ticket is opened at Friday 6pm and closed on Wednesday 6pm then if you calculate the SLA it will give you wrong data as typically the SLA timeframe should only include the business days. So we need to exclude the weekends from that time difference. Also suppose Monday is a global holiday the sometimes we need to exclude that as well.

Solution:

Suppose we have a List of WeekEnds and Holidays:

List<string> WeekEnds = new List<string>(){"Saturday","Sunday"};

List<DateTime> HolidayList = new List<DateTime>(){All your holidays};

Now calculate the time duration:

resolutionTime=EndDate.Subtract(StartDate);

Now exclude weekends and holidays:

int excludeDates = 0;
for (DateTime temp = resolutionSLAStartTime; temp < resolutionSLAEndTime; temp = temp.AddDays(1))
            {
                foreach (string day in WeekEnds)
                {
                    if (temp.DayOfWeek.ToString() == day)
                    {
                        excludeDates++;
                    }
                }

                foreach (DateTime holiday in HolidayList)
                {
                    if (temp == holiday)
                    {
                        excludeDates++;
                    }
                }

             }

            resolutionTime = resolutionTime.Subtract(new TimeSpan(excludeDates, 0, 0, 0));

Now the resolutionTime will give you the exact result you wanted.

COMMENT USING

Trending up