Home >Backend Development >C++ >How to Calculate Business Days Between Two Dates in C#?
Calculate working days between two dates in C#
In C#, calculating the number of working days between two dates is a very useful tool for scheduling, project management and other applications. There are a number of ways to accomplish this, taking into account weekends and possible bank holidays.
Use custom method:
One way is to create a custom method that manually calculates the number of working days. Here's an example:
<code class="language-csharp">public static int BusinessDaysUntil(DateTime firstDay, DateTime lastDay, params DateTime[] bankHolidays) { // 处理错误的结束日期 if (firstDay > lastDay) throw new ArgumentException("结束日期错误: " + lastDay); 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 == 7) //周日 businessDays -= 2; else if (lastDayOfWeek >= 6) //周六或周日 businessDays -= 1; if (firstDayOfWeek == 7) //周日 businessDays -= 1; } // 从完整周中减去周末天数 businessDays -= fullWeekCount * 2; // 减去银行假日 foreach (DateTime bankHoliday in bankHolidays) { DateTime bh = bankHoliday.Date; if (firstDay <= bh && bh <= lastDay) businessDays--; } return businessDays; }</code>
Bank holidays and custom inputs:
Additionally, the method can be extended to consider a list of bank holidays, ensuring accuracy even if these holidays occur mid-week. By providing a custom date list, you can handle specific scenarios.
Other methods:
C# provides other ways to calculate working days, such as using third-party libraries or the built-in System.Globalization.Calendar
class. However, the custom method described above provides a clear and straightforward implementation that meets the stated requirements.
The above is the detailed content of How to Calculate Business Days Between Two Dates in C#?. For more information, please follow other related articles on the PHP Chinese website!