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

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

Here is the code that I have come up with so far, but I have to mix between the NodaTime code and the .NET DateTime.DaysInMonth () method to achieve what I'm looking for that 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);

    }

}

Could you tell me what the recommended NodaTime method is to get the last day of the current and next months?

Thanks in advance

+3
source share
1 answer

Get Calendaryours ZonedDateTimeand then call 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));
+6
source

All Articles