Kotlin DateTimeParseException
The JVM ISO date parser rejects a calendar day that does not exist.
A simple example
DateTimeParseException
- Start with 2024-02-30
- Do this Validate the date
- Result Invalid date
Syntax
LocalDate.parse(text)
Run these examples in Kotlin
Save one example at a time as Lesson.kt. Use Kotlin 2.2 on JDK 21.
kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jarCheck a delivery date entered on a form
A grocery customer chooses February 30 as a delivery date. The booking desk needs to reject the impossible date and let the customer pick another day before a driver is scheduled.
import java.time.LocalDate
import java.time.format.DateTimeParseException
fun main() {
try {
println(LocalDate.parse("2025-02-30"))
} catch (problem: DateTimeParseException) {
println("Choose a valid date")
}
}
Choose a valid date
February 30 cannot be booked even though the input uses the expected year-month-day format.
Accept a leap-year rehearsal
The music room receives a booking request for the leap day in 2028. Validate the submitted ISO date before adding the booking to the schedule.
Reject a short-month overflow
A tutor tries to book the art room for the thirty-first day of April. Validate the submitted ISO date before adding the booking to the schedule.
What to watch for
Keep the parse call inside the handler and let unrelated failures propagate.