如何在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;
    }

其他回答

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

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

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

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

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

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

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

您可以按以下方式扩展DateTime;

public static class DateTimeMethods
{
    public static DateTime StartOfMonth(this DateTime date)
    {
        return new DateTime(date.Year, date.Month, 1, 0, 0, 0);
    }

    public static DateTime EndOfMonth(this DateTime date)
    {
        return date.StartOfMonth().AddMonths(1).AddSeconds(-1);
    }
}

像这样使用它;

DateTime today = DateTime.Now;

DateTime startOfMonth = today.StartOfMonth();
DateTime endOfMonth = today.EndOfMonth();