How do I get the last day of a month?

Solution 1:

The last day of the month you get like this, which returns 31:

DateTime.DaysInMonth(1980, 08);

Solution 2:

var lastDayOfMonth = DateTime.DaysInMonth(date.Year, date.Month);

Solution 3:

If you want the date, given a month and a year, this seems about right:

public static DateTime GetLastDayOfMonth(this DateTime dateTime)
{
    return new DateTime(dateTime.Year, dateTime.Month, DateTime.DaysInMonth(dateTime.Year, dateTime.Month));
}

Solution 4:

Substract a day from the first of next month:

DateTime lastDay = new DateTime(MyDate.Year,MyDate.Month+1,1).AddDays(-1);

Also, in case you need it to work for December too:

DateTime lastDay = new DateTime(MyDate.Year,MyDate.Month,1).AddMonths(1).AddDays(-1);

Solution 5:

You can find the last date of any month by this code:

var now = DateTime.Now;
var startOfMonth = new DateTime(now.Year, now.Month, 1);
var DaysInMonth = DateTime.DaysInMonth(now.Year, now.Month);
var lastDay = new DateTime(now.Year, now.Month, DaysInMonth);