5

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

  • A leap year February return 29
  • April returns 30.
  • December returns 31.

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

1 Answer 1

11

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.

1
  • Thanks, I was not familiar with TemporalAdjusters, but this worked well
    – MisterIbbs
    Commented Jul 10, 2020 at 7:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.