Library contents

Java DateTimeParseException

LocalDate.parse checks the calendar rules of the ISO date it reads. Invalid input throws DateTimeParseException.

A simple example

DateTimeParseException

  1. Start with 2024-02-30
  2. Do this Validate the date
  3. Result Invalid date
Even in the leap year 2024, February ends on the 29th.

Syntax

Java syntax
LocalDate.parse(text)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Check 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.

ResultChoose a valid date
Main.java
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");
        }
    }
}
Output
Choose a valid date

February 30 has the expected spelling for an ISO date but does not exist in the calendar.

Advertisements

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.

First output line2024 accepted
Main.java
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");
            }
        }
    }
}
Output
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.

Given2028-02-29
Worked resultBooking date accepted
Code and output in Java
Java source
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");
        }
    }
}
Output
Booking date accepted

What to watch for

A correctly shaped date can still be impossible. Use strict calendar parsing when the day must exist.

Documentation for DateTimeParseException