2016-09-26 85 views
-1

你如何減去工作日在C#在此基礎上添加工作日:如何減去工作日?

public static DateTime AddBusinessDays(DateTime date, int days = 5) 
    { 
     if (days < 0) 
     { 
      throw new ArgumentException("days cannot be negative", "days"); 
     } 

     if (days == 0) return date; 

     if (date.DayOfWeek == DayOfWeek.Saturday) 
     { 
      date = date.AddDays(2); 
      days -= 1; 
     } 
     else if (date.DayOfWeek == DayOfWeek.Sunday) 
     { 
      date = date.AddDays(1); 
      days -= 1; 
     } 

     date = date.AddDays(days/5 * 7); 
     int extraDays = days % 5; 

     if ((int)date.DayOfWeek + extraDays > 5) 
     { 
      extraDays += 2; 
     } 

     return date.AddDays(extraDays); 

    } 

,可以不採取負數,因此需要另外一個專門爲減去工作日。

編輯:「重複」問題是測量兩個日期之間的差異與工作日。我只想要一個開始日期和減去的天數以得到結果。 這是作爲一個函數完成的,而不是擴展名,正如你在AddDays中看到的那樣。

如上所見,沒有循環的方法將是最有效的。使用流利的DateTime

+3

可能重複[計算兩個日期之間的營業日數?](http://stackoverflow.com/questions/1617049/calculate-the-number-of-business-days-between-two-dates ) –

+0

@DarkBobG這不是我要找的。 –

回答

0

See this Answer

(鏈接答案已經被複制下面爲方便起見)

var now = DateTime.Now; 
var dateTime1 = now.AddBusinessDays(3); 
var dateTime2 = now.SubtractBusinessDays(5); 

內部代碼如下

/// <summary> 
/// Adds the given number of business days to the <see cref="DateTime"/>. 
/// </summary> 
/// <param name="current">The date to be changed.</param> 
/// <param name="days">Number of business days to be added.</param> 
/// <returns>A <see cref="DateTime"/> increased by a given number of business days.</returns> 
public static DateTime AddBusinessDays(this DateTime current, int days) 
{ 
    var sign = Math.Sign(days); 
    var unsignedDays = Math.Abs(days); 
    for (var i = 0; i < unsignedDays; i++) 
    { 
     do 
     { 
      current = current.AddDays(sign); 
     } 
     while (current.DayOfWeek == DayOfWeek.Saturday || 
      current.DayOfWeek == DayOfWeek.Sunday); 
    } 
    return current; 
} 

/// <summary> 
/// Subtracts the given number of business days to the <see cref="DateTime"/>. 
/// </summary> 
/// <param name="current">The date to be changed.</param> 
/// <param name="days">Number of business days to be subtracted.</param> 
/// <returns>A <see cref="DateTime"/> increased by a given number of business days.</returns> 
public static DateTime SubtractBusinessDays(this DateTime current, int days) 
{ 
    return AddBusinessDays(current, -days); 
} 
+0

安裝Fluent DateTime完成了這項工作。謝謝。 –