c#添加/减去工作日的日期时间

Aks*_*Aks 45 c# datetime

我有一个场景,给定一个date(DateTime),该日期加/减x天(达到DateTime.AddDays)必须加上或减去x工作日,即跳过周末和假日.我怎么能这样做呢?我应该实现自己的版本并将其附加到日历或其他东西?

Ale*_*idt 58

我建议您必须自己实现它,并在扩展方法中执行此操作:


public static class DateTimeExtensions
{
    public static DateTime AddWorkdays(this DateTime originalDate, int workDays)
    {
        DateTime tmpDate = originalDate;
        while (workDays > 0)
        {
            tmpDate = tmpDate.AddDays(1);
            if (tmpDate.DayOfWeek < DayOfWeek.Saturday && 
                tmpDate.DayOfWeek > DayOfWeek.Sunday &&
                !tmpDate.IsHoliday())
                workDays--;
        }
        return tmpDate;
    }

    public static bool IsHoliday(this DateTime originalDate)
    {
        // INSERT YOUR HOlIDAY-CODE HERE!
        return false;
    }
}

  • 此代码抛出一个`ArgumentOutOfRangeException`异常.也不处理负面日子. (5认同)
  • 对,我知道.此代码仅显示粗鲁的概念,并且必须实现更复杂.我认为,codeplex上有现成的库. (4认同)

Kev*_*Kev 56

基于Taz的 链接:

public static class DateTimeExtensions
{
  public static DateTime AddWorkDays(this DateTime date, int workingDays)
  {
    int direction = workingDays < 0 ? -1 : 1;
    DateTime newDate = date;
    while (workingDays != 0)
    {
      newDate = newDate.AddDays(direction);
      if (newDate.DayOfWeek != DayOfWeek.Saturday && 
          newDate.DayOfWeek != DayOfWeek.Sunday && 
          !newDate.IsHoliday())
      {
        workingDays -= direction;
      }
    }
    return newDate;
  }

  public static bool IsHoliday(this DateTime date)
  {
    // You'd load/cache from a DB or file somewhere rather than hardcode
    DateTime[] holidays = 
    new DateTime[] { 
      new DateTime(2010,12,27),
      new DateTime(2010,12,28),
      new DateTime(2011,01,03),
      new DateTime(2011,01,12),
      new DateTime(2011,01,13)
    };

    return holidays.Contains(date.Date);
  }
}
Run Code Online (Sandbox Code Playgroud)


Rik*_*ous 9

我最近用一点LINQ做了这个:

private DateTime CalculateFutureDate(DateTime fromDate, int numberofWorkDays, ICollection<DateTime> holidays)
{
    var futureDate = fromDate;
    var daterange = Enumerable.Range(1, numberofWorkDays * 2);
    var dateSet = daterange.Select (d => futureDate.AddDays(d));
    var dateSetElim = dateSet.Except(holidays).Except(dateSet.Where( s =>s.DayOfWeek == DayOfWeek.Sunday).Except(dateSet.Where  (s=>s.DayOfWeek==DayOfWeek.Saturday) ));

    //zero-based array
    futureDate = dateSetElim.ElementAt(numberofWorkDays-1);
    return futureDate;
}
Run Code Online (Sandbox Code Playgroud)