Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate Last Day of the Next Month

Tags:

c#

datetime

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);
like image 901
Brian Ashcraft Avatar asked Dec 17 '15 05:12

Brian Ashcraft


1 Answers

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

like image 173
Ben Voigt Avatar answered Oct 05 '22 12:10

Ben Voigt