Coder Perfect

How can I find out what day it is on the last day of the month?


In C#, how can I find the month’s last day?

How do I get the last day of month 8 (in this case 31) if I know the date 03/08/1980?

Asked by Gold

Solution #1

This is what you receive on the final day of the month: 31:

DateTime.DaysInMonth(1980, 08);

Answered by Oskar Kjellin

Solution #2

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

Answered by Mark

Solution #3

This seems about appropriate if you want the date given a month and a year:

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

Answered by Ian G

Solution #4

Subtract a day from the 1st of the following 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);

Answered by Radu094

Solution #5

This code can be used to discover the last date of any month:

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);

Answered by mash

Post is based on