2009-05-11 15 views
1

Ich habe folgendes Problem:Wie finden Sie den nächsten August? C#

Wir müssen den nächsten August finden. Ich andere Wörter, wenn wir 2009-09-01 sind, müssen wir 2010-08-31 wenn wir 2009-06-21 sind, brauchen wir 2009-08-31.

Ich weiß, ich kann überprüfen, ob heute kleiner ist als 31. August, aber ich frage mich, ob es eine andere Möglichkeit gibt.

+0

Als nächstes werden wir fragen, wie man ein int ... –

Antwort

16
public static class DateTimeExtensions 
    { 
     public static DateTime GetNextAugust31(this DateTime date) 
     { 
      return new DateTime(date.Month <= 8 ? date.Year : date.Year + 1, 8, 31); 
     } 
    } 
2

.Net 2,0

DateTime NextAugust(DateTime inputDate) 
    { 
     if (inputDate.Month <= 8) 
     { 
      return new DateTime(inputDate.Year, 8, 31); 
     } 
     else 
     { 
      return new DateTime(inputDate.Year+1, 8, 31); 
     } 
    } 
+1

Dies ist eigentlich falsch. Sie geben das Eingabedatum.Monat zurück, das nicht August wäre. Es wäre der Monat, der in die Methode geschickt wurde. – BFree

+0

hatte es eine 1 in 12 Chance zu arbeiten :) jetzt 0,2 für das ganze Jahr –

1
public static DateTime NextAugust(DateTime input) 
{ 
    switch(input.Month.CompareTo(8)) 
    { 
     case -1: 
     case 0: return new DateTime(input.Year, 8, 31); 
     case 1: 
      return new DateTime(input.Year + 1, 8, 31); 
     default: 
      throw new ApplicationException("This should never happen"); 
    } 
} 
1

Dies funktioniert. Achten Sie darauf, eine Ausnahmebehandlung hinzuzufügen. Wenn Sie beispielsweise eine 31 für feb übergeben haben, wird eine Ausnahme ausgelöst.

/// <summary> 
     /// Returns a date for the next occurance of a given month 
     /// </summary> 
     /// <param name="date">The starting date</param> 
     /// <param name="month">The month requested. Valid values (1-12)</param> 
     /// <param name="day">The day requestd. Valid values (1-31)</param> 
     /// <returns>The next occurance of the date.</returns> 
     public DateTime GetNextMonthByIndex(DateTime date, int month, int day) 
     { 
      // we are in the target month and the day is less than the target date 
      if (date.Month == month && date.Day <= day) 
       return new DateTime(date.Year, month, day); 

      //add month to date until we hit our month 
      while (true) 
      { 
       date = date.AddMonths(1); 
       if (date.Month == month) 
        return new DateTime(date.Year, month, day); 
      } 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      DateTime d = DateTime.Now;    

      //get the next august 
      Text = GetNextMonthByIndex(d, 8, 31).ToString(); 
     } 
Verwandte Themen