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?

assylias
  • 321,522
  • 82
  • 660
  • 783
MisterIbbs
  • 247
  • 1
  • 7
  • 20

1 Answers1

10

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.

assylias
  • 321,522
  • 82
  • 660
  • 783