javajava-timezoneddatetimedayofmonth

Get last day of the month from a ZonedDateTime object


I have previously been able to do this with Joda DateTime objects but i'm unsure how i can get the last day of a given month for a ZonedDateTime instance with a timezone applied.

e.g

With Jodatime i've used dayOfMonth() and getMaximumValue(), but how can I do the equivalent with ZonedDateTime in Java 11?


Solution

  • You don't really need a ZonedDateTime object for that - a LocalDate is probably enough (unless you are dealing with exotic calendars).

    val zdt = ZonedDateTime.now() //let's start with a ZonedDateTime if that's what you have
    val date = zdt.toLocalDate() //but a LocalDate is enough
    val endOfMonth = date.with(TemporalAdjusters.lastDayOfMonth())
    

    Note that you can also call zdt.with(TemporalAdjusters.lastDayOfMonth()) if you want to keep the time and timezone information.