簡體   English   中英

如何獲得當月的最后一天和下個月的最后一天

[英]How to get last day of current month and last day of next month

我想要獲得當月的最后一天和下個月的最后一天。

這是我到目前為止提出的代碼,但是我被迫在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推薦的方式來獲得當前和下個月的最后一天?

提前致謝

獲取ZonedDateTimeCalendar ,然后調用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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM