两个日期之间的小时数

时间:2016-03-10 11:31:27

标签: c# datetime

我有一个像这样的C#方法:

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

我有一张假期表,其中保存了所有假期。这个方法应该做的是计算startDate和startTime到endDate和endTime之间的小时数。它需要排除周末,也可以跳过两个日期之间的假期。

  

例如:

     

星期一到星期五上午9点到下午17点(8小时)工作。如果   startDate(1-3-2016)和startTime(9:00)以及endDate(10-3-2016)和   ENDTIME(13:00)。在我的假期表(8-3-2016)是假期然后它   应该返回52小时

1 个答案:

答案 0 :(得分:1)

我希望这能解决你的问题。

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;

如果您有一系列假期,例如DateTime[] bankHolidays,那么您也可以排除假期。

//减去时间间隔内的银行假日数

 foreach (DateTime bankHoliday in bankHolidays)
    {
        DateTime bh = bankHoliday.Date;
        if (firstDay <= bh && bh <= lastDay)
            --businessDays;
    }