Java DateTimeParseException
LocalDate.parse checks the calendar rules of the ISO date it reads. Invalid input throws DateTimeParseException.
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 Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaCheck 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;
class Main {
public static void main(String[] args) throws Exception {
try {
System.out.println(LocalDate.parse("2025-02-30"));
} catch (DateTimeParseException invalid) {
System.out.println("Choose a valid date");
}
}
}
Choose a valid date
February 30 has the expected spelling for an ISO date but does not exist in the calendar.
Book a real leap-day delivery
A florist accepts advance orders for leap day. The checkout must distinguish a real February 29 in a leap year from the same entry in an ordinary year.
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.util.List;
class Main {
public static void main(String[] args) throws Exception {
for (String date : List.of("2024-02-29", "2025-02-29")) {
try {
System.out.println(LocalDate.parse(date).getYear() + " accepted");
} catch (DateTimeParseException invalid) {
System.out.println(date.substring(0, 4) + " rejected");
}
}
}
}
2024 accepted 2025 rejected
ISO parsing accepts February 29 in 2024 and rejects it in 2025.
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.
Code and output in Java
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.concurrent.*;
class Main {
public static void main(String[] args) throws Exception {
try {
java.time.LocalDate.parse("2028-02-29");
System.out.println("Booking date accepted");
} catch (java.time.format.DateTimeParseException problem) {
System.out.println("Ask for a new date");
}
}
}
Booking date accepted
What to watch for
A correctly shaped date can still be impossible. Use strict calendar parsing when the day must exist.