0

I have a C# method like this:

public int GetWorkLogHours(DateTime? startDate, DateTime? endDate, string startTime, string endTime)
{
}

I have a table of Holiday in which all the holidays are saved. What this method supposed to do is to calculate the number of hours between the startDate and startTime to endDate and endTime.It needs to exclude weekends and also skip the holiday between the two dates.

For Example :

We work monday to friday 9:00 AM to 17:00 PM (8 hours). If the startDate(1-3-2016) and startTime(9:00) and endDate(10-3-2016) and endTime(13:00). In my Holiday table (8-3-2016) is holiday then it should return 52 hours

VVN
  • 1,607
  • 2
  • 16
  • 25
Xohair Shah
  • 39
  • 1
  • 8

1 Answers1

1

I hope this will solve your problem.

string start = "2016-01-07 09:00:00.000";
string end = "2016-01-07 17:00:00.000";
DateTime firstDay = Convert.ToDateTime(start);
DateTime lastDay = Convert.ToDateTime(end);

 if (firstDay > lastDay)
 {

 }
 else
 {
    TimeSpan span = lastDay - firstDay;
    int businessDays = span.Days + 1;
    int fullWeekCount = businessDays / 7;

    if (businessDays > fullWeekCount * 7)
            {
                int firstDayOfWeek = (int)firstDay.DayOfWeek;
                int lastDayOfWeek = (int)lastDay.DayOfWeek;
                if (lastDayOfWeek < firstDayOfWeek)
                    lastDayOfWeek += 7;
                if (firstDayOfWeek <= 6)
                {
                    if (lastDayOfWeek >= 7)
                        businessDays -= 2;
                    else if (lastDayOfWeek >= 6)
                        businessDays -= 1;
                }
                else if (firstDayOfWeek <= 7 && lastDayOfWeek >= 7)
                    businessDays -= 1;
            }

    businessDays -= fullWeekCount + fullWeekCount;
 }

 double hours = 8 * businessDays;

also if you have an array of holidays like, DateTime[] bankHolidays then you can exclude the holidays also.

// subtract the number of bank holidays during the time interval

 foreach (DateTime bankHoliday in bankHolidays)
    {
        DateTime bh = bankHoliday.Date;
        if (firstDay <= bh && bh <= lastDay)
            --businessDays;
    }
VVN
  • 1,607
  • 2
  • 16
  • 25