工作天数计算算法

忘是亡心i 2022-05-26 04:28 250阅读 0赞
  1. /// <summary>
  2. /// 根据指定时间段计算工作日天数
  3. /// </summary>
  4. /// <param name="firstDay">开始天数</param>
  5. /// <param name="lastDay">结束天数</param>
  6. /// <param name="bankHolidays">请假日期数组</param>
  7. /// <returns></returns>
  8. public static int BusinessDaysUntil(DateTime firstDay, DateTime lastDay, params DateTime[] bankHolidays)
  9. {
  10. firstDay = firstDay.Date;
  11. lastDay = lastDay.Date;
  12. if (firstDay > lastDay)
  13. throw new ArgumentException("最后一天不正确" + lastDay);
  14. TimeSpan span = lastDay - firstDay;
  15. int businessDays = span.Days + 1;
  16. int fullWeekCount = businessDays / 7;
  17. if (businessDays > fullWeekCount * 7)
  18. {
  19. int firstDayOfWeek = firstDay.DayOfWeek == DayOfWeek.Sunday ? 7 : (int)firstDay.DayOfWeek;
  20. int lastDayOfWeek = lastDay.DayOfWeek == DayOfWeek.Sunday ? 7 : (int)lastDay.DayOfWeek;
  21. if (lastDayOfWeek < firstDayOfWeek)
  22. lastDayOfWeek += 7;
  23. if (firstDayOfWeek <= 6)
  24. {
  25. if (lastDayOfWeek >= 7)
  26. businessDays -= 2;
  27. else if (lastDayOfWeek >= 6)
  28. businessDays -= 1;
  29. }
  30. else if (firstDayOfWeek <= 7 && lastDayOfWeek >= 7)
  31. businessDays -= 1;
  32. }
  33. businessDays -= fullWeekCount + fullWeekCount;
  34. foreach (DateTime bankHoliday in bankHolidays)
  35. {
  36. DateTime bh = bankHoliday.Date;
  37. if (firstDay <= bh && bh <= lastDay)
  38. --businessDays;
  39. }
  40. return businessDays;
  41. }

发表评论

表情:
评论列表 (有 0 条评论,250人围观)

还没有评论,来说两句吧...

相关阅读