如何在c#中找到一个月的最后一天?
例如,如果我有日期03/08/1980,我如何得到第8个月的最后一天(在本例中是31)?
如何在c#中找到一个月的最后一天?
例如,如果我有日期03/08/1980,我如何得到第8个月的最后一天(在本例中是31)?
当前回答
var lastDayOfMonth = DateTime.DaysInMonth(date.Year, date.Month);
其他回答
你可以通过一行代码找到这个月的最后一天:
int maxdt = (new DateTime(dtfrom.Year, dtfrom.Month, 1).AddMonths(1).AddDays(-1)).Day;
如果你想要日期,给定一个月和一年,这似乎是正确的:
public static DateTime GetLastDayOfMonth(this DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month, DateTime.DaysInMonth(dateTime.Year, dateTime.Month));
}
从下个月的第一天减去一天:
DateTime lastDay = new DateTime(MyDate.Year,MyDate.Month+1,1).AddDays(-1);
此外,如果你也需要它在12月工作:
DateTime lastDay = new DateTime(MyDate.Year,MyDate.Month,1).AddMonths(1).AddDays(-1);
另一种获取结束日期的方法:
private static DateTime GetMonthEndDate(DateTime date)
{
DateTime endDate = date;
int endDateMonth = endDate.Month;
while (endDateMonth == endDate.Month)
endDate = endDate.AddDays(1);
endDate = endDate.AddDays(-1);
return endDate;
}
// Use any date you want, for the purpose of this example we use 1980-08-03.
var myDate = new DateTime(1980,8,3);
var lastDayOfMonth = new DateTime(myDate.Year, myDate.Month, DateTime.DaysInMonth(myDate.Year, myDate.Month));