5
votes

I am attempting to use the DateTime function in C# to calculate the last day of next month.

For example, today is December 17th 2015. I want the DateTime function to return January 31st 2016 (the last day of next month).

I am using the following to calculate the first day of next month (this works):

DateTime firstDayNextMonth = DateTime.Today.AddDays(-DateTime.Now.Day+1).AddMonths(1);
5
Add months(2).addday(-1)?Giorgi Nakeuri
Given the astonishing number of wrong answers this question has attracted in less than ten minutes you can perhaps be forgiven for that keyboard mark on your forehead. Ignore the answers; you will spend more time trying to figure out what is wrong with each than it will take you to derive the correct answer. Go back to first principles. You have a current date. Can you work out what the month and year will be next month? Do so. Once you have that information, can you work out how many days that month has? Now you have the answer to your question: a year, a month, and a day.Eric Lippert
The title says last day, variable is first day. Do you know what date you want?Giorgi Nakeuri
OK, don't ignore Ben's answer.Eric Lippert
Most of the answer covered in stackoverflow.com/questions/2493032/… (which can be found using a search engine like bing.com/search?q=C%23+last+day+of+month )Alexei Levenkov

5 Answers

17
votes
DateTime reference = DateTime.Now;
DateTime firstDayThisMonth = new DateTime(reference.Year, reference.Month, 1);
DateTime firstDayPlusTwoMonths = firstDayThisMonth.AddMonths(2);
DateTime lastDayNextMonth = firstDayPlusTwoMonths.AddDays(-1);
DateTime endOfLastDayNextMonth = firstDayPlusTwoMonths.AddTicks(-1);

Demo: http://rextester.com/AKDI52378

2
votes
//system date or any date u want this case it is a calendar picker - 22/03/2016
DateTime today = dtpFrom.Value;

//Add a month to your date example , it now becomes - 22/04/2016
DateTime endOfMonth = new DateTime(today.Year, today.Month,today.Day).AddMonths(1);

//Get the last date off the above which is - 30
int getlastday = DateTime.DaysInMonth(endOfMonth.Year, endOfMonth.Month);

//Now set the date to the value  which will be the last day off the next month - 30/04/2016
DateTime newDate = new DateTime(endOfMonth.Year, endOfMonth.Month, getlastday);
0
votes
DateTime.DaysInMonth(DateTime.Now.AddMonths(1).Year, DateTime.Now.AddMonths(1).Month);
0
votes
 var lastDayInNextMonth = DateTime.DaysInMonth(DateTime.Now.AddMonths(1).Year, DateTime.Now.AddMonths(1).Month );  

@ Ben : DateTime.Now.AddMonths(1) will add 1 month to the current date not substract 11 months.

enter image description here

DateTime.Now.AddMonths(1).Year will give 2016 not 2015 refer the attached image

0
votes

try this:

int Day= DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month+1>12 ? 01 : DateTime.Now.Month+1 );