grady grady - 3 months ago 17
C# Question

DateTime.AddMonths adding only month not days

lets say, I have 28th of February 2010 and add one months to this date using

AddMonths(1)
...the resulting date is 28th of March, but not 31st of March, which I want. Is there a way to tweak that a bit so this works without adding custom code?

Edit: I don't need the last day of a month, actually I need to add one month, but when its the last day of a month, I need to find the last day of the next month.

Answer

I don't know what you want to achieve, but you could add one day, add a month and subtract one day.

DateTime nextMonth = date.AddDays(1).AddMonths(1).AddDays(-1);

EDIT:

As one of the commenters points out, this sometimes gives the wrong result. After reading your updated question, I think the easiest way of calculating the date you want is:

public static DateTime NextMonth(this DateTime date)
{
   if (date.Day != DateTime.DaysInMonth(date.Year, date.Month))
      return date.AddMonths(1);
   else 
      return date.AddDays(1).AddMonths(1).AddDays(-1);
}

This extension method returns next month's date. When the current date is the last day of the month, it will return the last day of next month.

Comments