你怎么找到这个月的最后一天?

Irw*_*win 91 c# datetime

可能重复:
如何获得一个月的最后一天?

到目前为止,我有这个:

DateTime createDate = new DateTime(year, month, 1).AddMonths(1).AddDays(-1);
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?

Jon*_*eet 224

如何使用DaysInMonth:

DateTime createDate = new DateTime (year, month,
                                    DateTime.DaysInMonth(year, month));
Run Code Online (Sandbox Code Playgroud)

(注意自己 - 必须在Noda Time中轻松实现......)

  • @BenJenkinson:哈 - 事实证明我*已经做过了 - "DateAdjusters.EndOfMonth". (3认同)
  • @JonSkeet 你有没有在 NodaTime 中让这变得简单,或者这仍然是最好的方法? (2认同)

Øyv*_*hen 23

您可以使用该方法DateTime.DaysInMonth(year,month)获取任何给定月份的天数.


Don*_*ald 7

这是我在CodePlex上有用的DateTime扩展库中找到的一种优雅方法:

http://datetimeextensions.codeplex.com/

这是一些示例代码:

    public static DateTime First(this DateTime current)
    {
        DateTime first = current.AddDays(1 - current.Day);
        return first;
    }

    public static DateTime First(this DateTime current, DayOfWeek dayOfWeek)
    {
        DateTime first = current.First();

        if (first.DayOfWeek != dayOfWeek)
        {
            first = first.Next(dayOfWeek);
        }

        return first;
    }

    public static DateTime Last(this DateTime current)
    {
        int daysInMonth = DateTime.DaysInMonth(current.Year, current.Month);

        DateTime last = current.First().AddDays(daysInMonth - 1);
        return last;
    }
Run Code Online (Sandbox Code Playgroud)

它还有一些其他有用的扩展,可能对您有所帮助.