views:

274

answers:

4

I have the following problem:

We need to find the next august. I other words if we are 2009-09-01 we need 2010-08-31 if we are 2009-06-21 we need 2009-08-31.

I know I can check if today is smaller than august 31 but I was wondering if there is an other possibility.

+15  A: 
    public static class DateTimeExtensions
    {
        public static DateTime GetNextAugust31(this DateTime date)
        {
            return new DateTime(date.Month <= 8 ? date.Year : date.Year + 1, 8, 31);
        }
    }
BFree
this is what I use right now, thx
Sem Dendoncker
+2  A: 

.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);
        }
    }
John Nolan
This is actually incorrect. You're returning the inputDate.Month, which wouldn't be August. It would be whatever month was sent in to the method.
BFree
it had a 1 in 12 chance of working :) now 0.2 for the whole year
John Nolan
+1  A: 
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");
 }
}
Chris Doggett
+1  A: 

This works. Be sure to add some exception handling. For example, if you passed in a 31 for feb, an exception will be thrown.

/// <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();
        }
Steve