Home >Backend Development >C++ >How to Efficiently Calculate the Number of Business Days Between Two Dates in C#?
How to efficiently calculate the number of working days between two dates in C#
Calculating the number of working days between two dates takes into account weekends and possible holidays. C# provides several ways to accomplish this task.
A suggested solution utilizes the DateTime
class to avoid inefficient day-by-day enumeration. This method calculates the number of working days in a specified interval by taking into account full weeks, partial weekends, and holidays. The algorithm is as follows:
.Date
attribute to convert the input date into the corresponding DateTime
object. TimeSpan
to calculate the span between dates and increment the weekday count by 1 for each day. The following is the implementation of the solution:
<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>
The above is the detailed content of How to Efficiently Calculate the Number of Business Days Between Two Dates in C#?. For more information, please follow other related articles on the PHP Chinese website!