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

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


当前回答

另一种获取结束日期的方法:

    private static DateTime GetMonthEndDate(DateTime date)
    {
        DateTime endDate = date;
        int endDateMonth = endDate.Month;

        while (endDateMonth == endDate.Month)
            endDate = endDate.AddDays(1);

        endDate = endDate.AddDays(-1);

        return endDate;
    }

其他回答

这将显示下个月的最后日期。可以从AddMonths(x)中添加或减去想要返回的月份。

DateTime.Now.AddMonths(2).AddDays(-DateTime.Now.Day)

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

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

如果你想要日期,给定一个月和一年,这似乎是正确的:

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

你可以通过一行代码找到这个月的最后一天:

int maxdt = (new DateTime(dtfrom.Year, dtfrom.Month, 1).AddMonths(1).AddDays(-1)).Day;

从DateTimePicker:

第一次约会:

DateTime first_date = new DateTime(DateTimePicker.Value.Year, DateTimePicker.Value.Month, 1);

最后的日期:

DateTime last_date = new DateTime(DateTimePicker.Value.Year, DateTimePicker.Value.Month, DateTime.DaysInMonth(DateTimePicker.Value.Year, DateTimePicker.Value.Month));