如何在c#中找到一个月的最后一天?
例如,如果我有日期03/08/1980,我如何得到第8个月的最后一天(在本例中是31)?
如何在c#中找到一个月的最后一天?
例如,如果我有日期03/08/1980,我如何得到第8个月的最后一天(在本例中是31)?
当前回答
你可以通过一行代码找到这个月的最后一天:
int maxdt = (new DateTime(dtfrom.Year, dtfrom.Month, 1).AddMonths(1).AddDays(-1)).Day;
其他回答
另一种获取结束日期的方法:
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;
}
你可以通过下面的代码找到任何月份的最后一天:
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);
var lastDayOfMonth = DateTime.DaysInMonth(date.Year, date.Month);
我只想在每个月的最后一天发射代码,就是这么简单……
if (DateTime.UtcNow.AddDays(1).Day != 1)
{
// Tomorrow is not the first...
return;
}
这个月的最后一天你会得到这样的结果,返回31:
DateTime.DaysInMonth(1980, 08);