如何在c#中找到一个月的最后一天?
例如,如果我有日期03/08/1980,我如何得到第8个月的最后一天(在本例中是31)?
如何在c#中找到一个月的最后一天?
例如,如果我有日期03/08/1980,我如何得到第8个月的最后一天(在本例中是31)?
当前回答
这将显示下个月的最后日期。可以从AddMonths(x)中添加或减去想要返回的月份。
DateTime.Now.AddMonths(2).AddDays(-DateTime.Now.Day)
其他回答
var lastDayOfMonth = DateTime.DaysInMonth(date.Year, date.Month);
例如2021年5月7日
DateTime.Now.Day;
结果:5
DateTime.Now.AddMonths(+1).AddDays(-DateTime.Now.Day).ToString(“yyyy-MM-dd”);
结果:2021/07/31
另一种获取结束日期的方法:
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;
}
这个月的最后一天你会得到这样的结果,返回31:
DateTime.DaysInMonth(1980, 08);
我只想在每个月的最后一天发射代码,就是这么简单……
if (DateTime.UtcNow.AddDays(1).Day != 1)
{
// Tomorrow is not the first...
return;
}