2011-01-11 69 views
131

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

+0

DateTime.DaysInMonth(1980,08); 请看这篇文章http://stackoverflow.com/questions/2493032/how-to-get-the-last-day-of-a-month – 2014-01-29 12:08:02

回答

284

做的另一种方式:

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

我正要建议System.Globalization.CultureInfo.CurrentCulture.Calendar.GetDaysInMonth.GetDaysInMonth,但这种方法更短。 – hultqvist 2011-01-11 07:40:25

57

喜欢的东西:

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

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

+1

正是我想写的,但认为有人会打我到它:) +1 – leppie 2011-01-11 07:22:07

+8

Humm ..如果它在你的代码中的许多地方被重复使用,把它写成dateTime类的扩展方法,你可以在DateTime.Now上调用它。例如。 DateTime.Now.LastDayOfMonth(); – 2011-01-11 07:25:28

-7

尝试。它会解决你的问题。

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

构建一个`string`,以便[解析为`DateTime`](http://msdn.microsoft.com/library/xhz1w05e.aspx#remarksToggle)效率低下,并且依赖于当前文化的日期格式。其他三年的答案提供了更清洁的解决方案。 – BACON 2014-02-25 05:33:39

7
public static class DateTimeExtensions 
{ 
    public static DateTime LastDayOfMonth(this DateTime date) 
    { 
     return date.AddDays(1-(date.Day)).AddMonths(1).AddDays(-1); 
    } 
} 
3
DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month) 
相关问题