Akshay J
Akshay J

Reputation: 5458

Need to find last day of previous month and previous to previous month

I have to find the last date of last month(Nov) and a month before that(Oct).
I used the following code:

DateTime today = DateTime.Today;
DateTime endOfLastMonth = new DateTime(today.Year, today.Month - 1, 1).AddMonths(1).AddDays(-1);
DateTime endOfLastLastMonth = new DateTime(today.Year, today.Month - 2, 1).AddMonths(1).AddDays(-1); 

The code works well for today but in the month of Jan the code fails because it supplies month part as 0 and -1.

Please let me know how to do that.
For the month of jan it should say 31 dec and 30 Nov.

Upvotes: 0

Views: 1526

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499730

The simplest way to find the last day of the previous month is to just find the first day of the current month (which will always be valid), and then subtract one day. Then do the same thing for the previous month.

DateTime startOfMonth = new DateTime(today.Year, today.Month, 1);
DateTime endOfPreviousMonth = startOfMonth.AddDays(-1);
DateTime endOfPreviousPreviousMonth = startOfMonth.AddMonths(-1).AddDays(-1);

Upvotes: 18

Related Questions