gpt4 book ai didi

c# - 计算两个日期之间的工作日数?

转载 作者:IT王子 更新时间:2023-10-29 03:38:51 27 4
gpt4 key购买 nike

在 C# 中,如何计算两个日期之间的工作日(或工作日)天数?

最佳答案

我以前遇到过这样的任务,我已经找到了解决方案。在可以避免的情况下,我会避免列举中间的所有日子,这里就是这种情况。正如我在上面的一个答案中看到的那样,我什至没有提到创建一堆 DateTime 实例。这实在是浪费处理能力。特别是在现实世界的情况下,当您必须检查几个月的时间间隔时。在下面查看我的代码和注释。

    /// <summary>
/// Calculates number of business days, taking into account:
/// - weekends (Saturdays and Sundays)
/// - bank holidays in the middle of the week
/// </summary>
/// <param name="firstDay">First day in the time interval</param>
/// <param name="lastDay">Last day in the time interval</param>
/// <param name="bankHolidays">List of bank holidays excluding weekends</param>
/// <returns>Number of business days during the 'span'</returns>
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;
// find out if there are weekends during the time exceedng the full weeks
if (businessDays > fullWeekCount*7)
{
// we are here to find out if there is a 1-day or 2-days weekend
// in the time interval remaining after subtracting the complete weeks
int firstDayOfWeek = (int) firstDay.DayOfWeek;
int lastDayOfWeek = (int) lastDay.DayOfWeek;
if (lastDayOfWeek < firstDayOfWeek)
lastDayOfWeek += 7;
if (firstDayOfWeek <= 6)
{
if (lastDayOfWeek >= 7)// Both Saturday and Sunday are in the remaining time interval
businessDays -= 2;
else if (lastDayOfWeek >= 6)// Only Saturday is in the remaining time interval
businessDays -= 1;
}
else if (firstDayOfWeek <= 7 && lastDayOfWeek >= 7)// Only Sunday is in the remaining time interval
businessDays -= 1;
}

// subtract the weekends during the full weeks in the interval
businessDays -= fullWeekCount + fullWeekCount;

// subtract the number of bank holidays during the time interval
foreach (DateTime bankHoliday in bankHolidays)
{
DateTime bh = bankHoliday.Date;
if (firstDay <= bh && bh <= lastDay)
--businessDays;
}

return businessDays;
}

Slauma 编辑,2011 年 8 月

很好的答案!虽然有小错误。由于回答者自 2009 年以来一直缺席,因此我可以自由编辑此答案。

上面的代码假定 DayOfWeek.Sunday 的值为 7,但事实并非如此。该值实际上是 0。例如,如果 firstDaylastDay 都是同一个星期日,则会导致计算错误。在这种情况下,该方法返回 1,但它应该是 0

此错误的最简单修复方法:在代码中替换 firstDayOfWeeklastDayOfWeek 声明如下的行:

int firstDayOfWeek = firstDay.DayOfWeek == DayOfWeek.Sunday 
? 7 : (int)firstDay.DayOfWeek;
int lastDayOfWeek = lastDay.DayOfWeek == DayOfWeek.Sunday
? 7 : (int)lastDay.DayOfWeek;

现在的结果是:

  • 周五到周五 -> 1
  • 周六到周六 -> 0
  • 周日到周日 -> 0
  • 周五到周六 -> 1
  • 周五到周日 -> 1
  • 周五到周一 -> 2
  • 周六至周一 -> 1
  • 周日到周一 -> 1
  • 周一到周一 -> 1

关于c# - 计算两个日期之间的工作日数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1617049/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com