如何在c#中找到一个月的最后一天?

例如,如果我有日期03/08/1980,我如何得到第8个月的最后一天(在本例中是31)?


当前回答

// Use any date you want, for the purpose of this example we use 1980-08-03.
var myDate = new DateTime(1980,8,3);
var lastDayOfMonth = new DateTime(myDate.Year, myDate.Month, DateTime.DaysInMonth(myDate.Year, myDate.Month));

其他回答

这个月的最后一天你会得到这样的结果,返回31:

DateTime.DaysInMonth(1980, 08);

从下个月的第一天减去一天:

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

此外,如果你也需要它在12月工作:

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

你可以通过下面的代码找到任何月份的最后一天:

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

例如2021年5月7日

DateTime.Now.Day;

结果:5

DateTime.Now.AddMonths(+1).AddDays(-DateTime.Now.Day).ToString(“yyyy-MM-dd”);

结果:2021/07/31

要获得特定日历中一个月的最后一天-并在扩展方法中-:

public static int DaysInMonthBy(this DateTime src, Calendar calendar)
{
    var year = calendar.GetYear(src);                   // year of src in your calendar
    var month = calendar.GetMonth(src);                 // month of src in your calendar
    var lastDay = calendar.GetDaysInMonth(year, month); // days in month means last day of that month in your calendar
    return lastDay;
}