2016-09-26 3 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); 

    } 

編集:「複製」の質問は、2つの日付の差を営業日とともに測定していることです。私はちょうど開始日と、結果を思い付くために減算する日数が欲しい。 これは、上記のAddDaysのように、拡張機能ではなく、関数として行う必要があります。

上記のようにループのない方法が最も効率的です。

+3

[2つの日付間の営業日数を計算しますか?](http://stackoverflow.com/questions/1617049/calculate-the-number-of-business-days-between-two-dates ) –

+0

@DarkBobGそれは私が探しているものではありません。 –

答えて

0

See this Answer

(リンクされた答えは、便宜上、下に複製された)流暢のDateTimeを使用して

を次のように

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をインストールするとその仕事が完了しました。ありがとう。 –

関連する問題