2010-03-22 72 views
209

如何在C#中查找月份的最後一天?我如何獲得一個月的最後一天?

例如,如果我有日期03/08/1980,我如何獲得第8個月的最後一天(在這種情況下爲31)?

+2

@Mark:我可以問什麼?我想,你自己的答案不需要擴展方法。 – abatishchev 2010-03-22 14:48:46

+4

最後一天不是特定的月份,你也需要一年。 2010年2月的最後一天是28天,但2008年2月的最後一天是29天。 – Guffa 2010-03-22 14:49:22

+0

@abatishchev它並不需要擴展方法,但問題並不真正需要。但是,至少對我來說,它看起來好多了,而且更具可讀性。擴展方法比任何其他建議都更有意義。任何解決方案都可以在擴展方法中使用,而不僅僅是我的。 – Mark 2010-03-22 14:50:59

回答

414

你得到這樣的月份,返回31年的最後一天:如果你想日期

DateTime.DaysInMonth(1980, 08); 
+14

public static DateTime ConvertToLastDayOfMonth(DateTime date) 返回新的DateTime(date.Year,date.Month, } 以日期格式獲得月份的最後一天 – regisbsb 2014-12-16 00:38:38

65
DateTime firstOfNextMonth = new DateTime(date.Year, date.Month, 1).AddMonths(1); 
DateTime lastOfThisMonth = firstOfNextMonth.AddDays(-1); 
+1

「如何獲得一個月的最後一天?」。 DateTime.DaysInMonth(年,月)將返回當月有多少天,這將返回「月份的最後一天是什麼」的相同答案。你的方式有效,但我認爲對於一件簡單的事情來說代碼太多了。 – rochasdv 2016-01-19 11:55:02

9

。減去從第一下個月的一天:

DateTime lastDay = new DateTime(MyDate.Year,MyDate.Month+1,1).AddDays(-1); 

此外,如果你需要它的月工作太:

DateTime lastDay = new DateTime(MyDate.Year,MyDate.Month,1).AddMonths(1).AddDays(-1); 
138
var lastDayOfMonth = DateTime.DaysInMonth(date.Year, date.Month); 
+0

@Henk其實我從我們的源代碼中的一個地方,從'lastDayOfMonth'創建'DateTime'。誠實地說,無論哪種方式都很好。這是一種迂腐的理由,哪種方式更好。我已經完成了這兩個方面,都產生了相同的答案。 – Mark 2010-03-22 15:02:14

+0

Mark,no。你的結果是'int',我的'DateTime'。它關於我們誰讀了(猜測)最好的規格。 – 2010-03-22 15:09:05

1

我不我不知道C#,但是,如果事實證明沒有一種方便的API來獲取它,你可以這樣做的方法之一是遵循以下邏輯:

today -> +1 month -> set day of month to 1 -> -1 day 

當然,假設你有這種類型的日期數學。

23

,給予一個月,一年,這個比較合適:

public static DateTime GetLastDayOfMonth(this DateTime dateTime) 
{ 
    return new DateTime(dateTime.Year, dateTime.Month, DateTime.DaysInMonth(dateTime.Year, dateTime.Month)); 
} 
6

您可以通過這個代碼中找到任何一個月的最後日期:

var now = DateTime.Now; 
var startOfMonth = new DateTime(now.Year, now.Month, 1); 
var DaysInMonth = DateTime.DaysInMonth(now.Year, now.Month); 
var lastDay = new DateTime(now.Year, now.Month, DaysInMonth); 
8

您可以通過一個單一的代碼行找到該月的最後一天:

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

我想知道,不是簡單的方法:'DateTime.DaysInMonth',爲什麼有人應該尋找這種不可讀和複雜的方式來實現它!? - 但作爲一個有效的解決方案是可以接受的;)。 – 2017-09-10 09:11:45

3

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

在特定的日曆中以及在擴展方法中獲取月份的最後一天 - :

public static int DaysInMonthBy(this DateTime src, Calendar calendar) 
{ 
    var year = calendar.GetYear(src);     // year of src in your calendar 
    var month = calendar.GetMonth(src);     // month of src in your calendar 
    var lastDay = calendar.GetDaysInMonth(year, month); // days in month means last day of that month in your calendar 
    return lastDay; 
} 
相關問題