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.
You need to use DateTime. Now. AddMonths(1). Month .
ToInt16( d[1]); int year =Convert. ToInt16( d[2]); DateTime newdate =new DateTime(year, month, day). AddMonths(3);
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With