Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.AddMonths adding only month not days

Tags:

c#

datetime

Let's say, I have 28th of February 2010 and add one month to this date using AddMonths(1)...
the resulting date is March 28th, 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.

like image 359
grady Avatar asked Jun 17 '10 09:06

grady


People also ask

How can I add 1 month to date in asp net?

You need to use DateTime. Now. AddMonths(1). Month .

How can I add 3 months to current date in asp net?

ToInt16( d[1]); int year =Convert. ToInt16( d[2]); DateTime newdate =new DateTime(year, month, day). AddMonths(3);

How can I get only the date from DateTime format?

ToString() − One more way to get the date from DateTime is using ToString() extension method. The advantage of using ToString() extension method is that we can specify the format of the date that we want to fetch. DateTime. Date − will also remove the time from the DateTime and provides us the Date only.


1 Answers

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.

like image 128
Philippe Leybaert Avatar answered Oct 20 '22 15:10

Philippe Leybaert