DateTime.AddMonths adding only month not days

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)