Question

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

Was it helpful?

Solution

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));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top