如何在C#中获得本月的最后一天?

时间:2011-01-11 07:19:23

标签: c#

如何在C#中找到该月的最后一天?

5 个答案:

答案 0 :(得分:325)

另一种方法:

DateTime today = DateTime.Today;
DateTime endOfMonth = new DateTime(today.Year, 
                                   today.Month, 
                                   DateTime.DaysInMonth(today.Year, 
                                                        today.Month));

答案 1 :(得分:61)

类似的东西:

DateTime today = DateTime.Today;
DateTime endOfMonth = new DateTime(today.Year, today.Month, 1).AddMonths(1).AddDays(-1);

也就是说你得到下个月的第一天,然后减去一天。框架代码将处理月份长度,闰年等事情。

答案 2 :(得分:9)

public static class DateTimeExtensions
{
    public static DateTime LastDayOfMonth(this DateTime date)
    {
        return date.AddDays(1-(date.Day)).AddMonths(1).AddDays(-1);
    }
}

答案 3 :(得分:5)

DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month)

答案 4 :(得分:-7)

试试这个。它会解决你的问题。

 var lastDayOfMonth = DateTime.DaysInMonth(int.Parse(ddlyear.SelectedValue), int.Parse(ddlmonth.SelectedValue));
DateTime tLastDayMonth = Convert.ToDateTime(lastDayOfMonth.ToString() + "/" + ddlmonth.SelectedValue + "/" + ddlyear.SelectedValue);