简体   繁体   中英

How to get last day of current month and last day of next month

I'm trying to get the last day of the current month and the last day of the next month.

Here's the code I've come up with so far, but I'm forced to mix between NodaTime code and the .NET method DateTime.DaysInMonth() to achieve what I'm looking for, which doesn't sound right.

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

    }

}

Can you please let me know what is the NodaTime recommended way to get the last day of the current and next months?

Thanks in advance

Get the Calendar of your ZonedDateTime and then call the GetDaysInMonth(year, month) method:

ZonedDateTime mstNow = now.InZone(mst);
CalendarSystem calendar = mstNow.Calendar;
LocalDate mstLastDayOfCurrentMonth = new LocalDate(
    mstNow.Year, mstNow.Month, calendar.GetDaysInMonth(mstNow.Year, mstNow.Month));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM