2010-03-09 205 views
27

通常我使用下面的代碼,但有沒有更好的方法?.NET中每個月的最後一天

lastOfMonth = new DateTime(Now.Year, Now.Month, 1).AddMonths(1).AddDays(-1) 
+3

定義「更好」。 –

+0

我認爲只有API提供的功能會做得更好。 –

+1

你想要一個特定的時間嗎?如果不是,你應該使用今天,而不是現在。 –

回答

49

我用

DateTime now = DateTime.Today; 
var lastDate = new DateTime(now.Year, now.Month, DateTime.DaysInMonth(now.Year, now.Month)); 
8
DateTime(year, month, DateTime.DaysInMonth(year, month)). 
3

您可以使用CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(Now.Year,Now.Month)

12

我可能會使用DaysInMonth,因爲它使代碼更易讀易懂(儘管我非常喜歡你的技巧:-))。這requieres打字的類似ammount的(這是相當多),所以我可能會定義一個擴展方法:

DateTime LastDayOfMonth(this DateTime) { 
    var days = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month); 
    return new DateTime(DateTime.Now.Year, DateTime.Now.Month, days); 
} 

現在我們可以使用DateTime.Now.LastDayOfMonth()看起來好多了:-)。

2

這裏是如何使用Noda Time獲得當月的天數:

int days = CalendarSystem.Iso.GetDaysInMonth(year, month); 

很簡單,不是嗎?那麼假設你知道你所問的年份和月份。如果你想它的當前個月,並在系統時區,那麼你必須指定明確的,就像這樣:

DateTimeZone tz = DateTimeZoneProviders.Tzdb.GetSystemDefault(); 
LocalDate localDate = SystemClock.Instance.Now.InZone(tz).Date; 
int days = localDate.Calendar.GetDaysInMonth(localDate.Year, localDate.Month); 

野田佳彥時故意讓你覺得這些事情,而不是隻是作出DateTime.NowDateTime.Today這樣的假設。

相關問題