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

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


当前回答

如果你想要日期,给定一个月和一年,这似乎是正确的:

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

其他回答

您可以按以下方式扩展DateTime;

public static class DateTimeMethods
{
    public static DateTime StartOfMonth(this DateTime date)
    {
        return new DateTime(date.Year, date.Month, 1, 0, 0, 0);
    }

    public static DateTime EndOfMonth(this DateTime date)
    {
        return date.StartOfMonth().AddMonths(1).AddSeconds(-1);
    }
}

像这样使用它;

DateTime today = DateTime.Now;

DateTime startOfMonth = today.StartOfMonth();
DateTime endOfMonth = today.EndOfMonth();

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

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

我不懂c#,但是,如果没有一个方便的API方法来获得它,其中一种方法是遵循以下逻辑:

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

当然,前提是你有这种类型的约会数学。

你可以通过一行代码找到这个月的最后一天:

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

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

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