C#中高效计算两个日期之间工作日数的方法
计算两个日期之间的工作日数需要考虑周末和可能的节假日。C# 提供多种方法来完成此任务。
一种建议的解决方案利用 DateTime
类,避免低效的逐日枚举。此方法通过考虑完整周、部分周末和节假日来计算指定时间间隔内工作日数。算法如下:
.Date
属性将输入日期转换为相应的 DateTime
对象。TimeSpan
计算日期之间的跨度,并为每一天将工作日计数增加 1。以下是解决方案的实现:
<code class="language-csharp">public static int BusinessDaysUntil(this DateTime firstDay, DateTime lastDay, params DateTime[] bankHolidays) { firstDay = firstDay.Date; lastDay = lastDay.Date; if (firstDay > lastDay) throw new ArgumentException("Incorrect last day " + lastDay); TimeSpan span = lastDay - firstDay; int businessDays = span.Days + 1; int fullWeekCount = businessDays / 7; // 计算周末天数 int weekendDays = fullWeekCount * 2; int remainingDays = businessDays % 7; int firstDayOfWeek = (int)firstDay.DayOfWeek; int lastDayOfWeek = (int)lastDay.DayOfWeek; if (remainingDays > 0) { if (lastDayOfWeek == 0) lastDayOfWeek = 7; // 将周日转换为7 if (firstDayOfWeek == 0) firstDayOfWeek = 7; // 将周日转换为7 if (lastDayOfWeek < 6) weekendDays += 0; // 如果最后一天不是周末,则不加周末天数 else if (lastDayOfWeek == 6) weekendDays += 1; // 如果最后一天是周六,则加一天 else weekendDays += 2; // 如果最后一天是周日,则加两天 if (firstDayOfWeek == 7) weekendDays -= 1; // 如果第一天是周日,则减一天 else if (firstDayOfWeek == 6) weekendDays -= 1; // 如果第一天是周六,则减一天 } businessDays -= weekendDays; foreach (DateTime bankHoliday in bankHolidays) { DateTime bh = bankHoliday.Date; if (bh >= firstDay && bh <= lastDay) businessDays--; } return businessDays; }</code>
以上是如何在C#中高效计算两个日期之间的工作日数?的详细内容。更多信息请关注PHP中文网其他相关文章!