如何在c#中找到一个月的最后一天?

例如,如果我有日期03/08/1980,我如何得到第8个月的最后一天(在本例中是31)?


当前回答

我只想在每个月的最后一天发射代码,就是这么简单……

if (DateTime.UtcNow.AddDays(1).Day != 1)
{
    // Tomorrow is not the first...
    return;
}

其他回答

这个公式反映了@RHSeeger的想法,作为一个简单的解决方案,以获得(在这个例子中)第3个月的最后一天(单元格A1 + 4中的日期月份,该月的第一天减去1天):

=DATE(YEAR(A1);MONTH(A1)+4;1)-1

非常精确,包括闰年的二月。

var lastDayOfMonth = DateTime.DaysInMonth(date.Year, date.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);

我只想在每个月的最后一天发射代码,就是这么简单……

if (DateTime.UtcNow.AddDays(1).Day != 1)
{
    // Tomorrow is not the first...
    return;
}

例如2021年5月7日

DateTime.Now.Day;

结果:5

DateTime.Now.AddMonths(+1).AddDays(-DateTime.Now.Day).ToString(“yyyy-MM-dd”);

结果:2021/07/31