3

我正在尝试获取本月的最后一天和下个月的最后一天。

这是我到目前为止提出的代码,但我不得不在 NodaTime 代码和 .NET 方法 DateTime.DaysInMonth() 之间混合以实现我正在寻找的东西,这听起来不对。

class Program {

    public static void Main(string[] args)
    {
        DateTimeZone mst = DateTimeZoneProviders.Tzdb["MST"];

        Instant now = SystemClock.Instance.Now;
        ZonedDateTime mstNow = now.InZone(mst);

        LocalDate mstLastDayOfCurrentMonth = new LocalDate(mstNow.Year, mstNow.Month, DateTime.DaysInMonth(mstNow.Year, mstNow.Month));
        Console.WriteLine("Last Day of Current Month: {0}", mstLastDayOfCurrentMonth);

        //move into the next month
        LocalDate nextMonth = mstLastDayOfCurrentMonth.PlusDays(1);
        LocalDate mstLastDayOfNextMonth = new LocalDate(nextMonth.Year, nextMonth.Month, DateTime.DaysInMonth(nextMonth.Year, nextMonth.Month)); 
        Console.WriteLine("Last Day of Next Month: {0}", mstLastDayOfNextMonth);

    }

}

您能否让我知道 NodaTime 推荐的获取当前和下个月最后一天的方法是什么?

提前致谢

4

1 回答 1

10

获取Calendar您的ZonedDateTime,然后调用该GetDaysInMonth(year, month)方法:

ZonedDateTime mstNow = now.InZone(mst);
CalendarSystem calendar = mstNow.Calendar;
LocalDate mstLastDayOfCurrentMonth = new LocalDate(
    mstNow.Year, mstNow.Month, calendar.GetDaysInMonth(mstNow.Year, mstNow.Month));
于 2014-02-14T20:25:18.487 回答