How to find next August? FROM#

I have the following problem:

We need to find next August. I am different 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 less than August 31st, but I was wondering if there is another possibility.

+1


a source to share


4 answers


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

      



+16


a source


.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);
        }
    }

      

+2


a source


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


a source


It works. Be sure to add exception handling. For example, if you go to 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();
        }

      

+1


a source







All Articles