Get last day of the month from a ZonedDateTime object
Asked Answered
H

1

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?

Halvah answered 23/6, 2020 at 19:32 Comment(0)
B
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.

Bandmaster answered 23/6, 2020 at 20:35 Comment(1)
Thanks, I was not familiar with TemporalAdjusters, but this worked wellHalvah

© 2022 - 2024 — McMap. All rights reserved.