2011-01-11 117 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) 
相關問題