2011-01-06 2 views
0

Wie subtrahiere ich eine Anzahl von Geschäftstagen (nicht Sa oder Sonntag) von einer DateTime?Wie subtrahiere ich eine Anzahl von Geschäftstagen (nicht Sa oder Sonntag) von einer DateTime?

sollte die Methode Signatur sein:

Leere SubtractBusinessDays (ref Datetime dt, int BusinessDaysToSubtract)

Dank

+1

duplizieren: http://Stackoverflow.com/questions/4384263/Adding-workdays-to-date-taking-intoaccount-weekends-and-holidays (Subtraktion = negative add) –

+0

@Hans, nicht genau ein Betrogener von dieser Frage, aber ich weiß es ** ist ** ein Betrogener. – Brad

Antwort

2

Hier ist eine Erweiterung Methode, die Sie verwenden können. Fühlen Sie sich frei, es als eine einfache Methode umzuformen.

/// <summary> 
/// Adds weekdays to date 
/// </summary> 
/// <param name="value">DateTime to add to</param> 
/// <param name="weekdays">Number of weekdays to add</param> 
/// <returns>DateTime</returns> 
public static DateTime AddWeekdays(this DateTime value, int weekdays) 
{ 
    int direction = Math.Sign(weekdays); 
    int initialDayOfWeek = Convert.ToInt32(value.DayOfWeek); 

    //--------------------------------------------------------------------------- 
    // if the day is a weekend, shift to the next weekday before calculating 
    if ((value.DayOfWeek == DayOfWeek.Sunday && direction < 0) 
     || (value.DayOfWeek == DayOfWeek.Saturday && direction > 0)) 
    { 
     value = value.AddDays(direction * 2); 
     weekdays += (direction * -1); // adjust days to add by one 
    } 
    else if ((value.DayOfWeek == DayOfWeek.Sunday && direction > 0) 
     || (value.DayOfWeek == DayOfWeek.Saturday && direction < 0)) 
    { 
     value = value.AddDays(direction); 
     weekdays += (direction * -1); // adjust days to add by one 
    } 
    //--------------------------------------------------------------------------- 

    int weeksBase = Math.Abs(weekdays/5); 
    int addDays = Math.Abs(weekdays % 5); 

    int totalDays = (weeksBase * 7) + addDays; 
    DateTime result = value.AddDays(totalDays * direction); 

    //--------------------------------------------------------------------------- 
    // if the result is a weekend, shift to the next weekday 
    if ((result.DayOfWeek == DayOfWeek.Sunday && direction > 0) 
     || (result.DayOfWeek == DayOfWeek.Saturday && direction < 0)) 
    { 
     result = result.AddDays(direction); 
    } 
    else if ((result.DayOfWeek == DayOfWeek.Sunday && direction < 0) 
     || (result.DayOfWeek == DayOfWeek.Saturday && direction > 0)) 
    { 
     result = result.AddDays(direction * 2); 
    } 
    //--------------------------------------------------------------------------- 

    return result; 
} 
0

Könnten Sie nicht nur die Anzahl der Tage erhalten, mod dann 7 und subtrahieren, dass Wert * 2 von der ursprünglichen Anzahl der Tage, dann subtrahiert 1 oder 2, wenn der aktuelle Tag jeweils Samstag oder Sonntag ist?

Verwandte Themen