我如何获得一个月的最后一天?

问题描述:

如何在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

你得到这样的月份,返回31年的最后一天:如果你想日期

DateTime.DaysInMonth(1980, 08); 
+14

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

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

。减去从第一下个月的一天:

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

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

我不我不知道C#,但是,如果事实证明没有一种方便的API来获取它,你可以这样做的方法之一是遵循以下逻辑:

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

当然,假设你有这种类型的日期数学。

,给予一个月,一年,这个比较合适:

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

您可以通过这个代码中找到任何一个月的最后日期:

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

您可以通过一个单一的代码行找到该月的最后一天:

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

我想知道,不是简单的方法:'DateTime.DaysInMonth',为什么有人应该寻找这种不可读和复杂的方式来实现它!? - 但作为一个有效的解决方案是可以接受的;)。 – 2017-09-10 09:11:45

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

在特定的日历中以及在扩展方法中获取月份的最后一天 - :

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; 
}