Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java strict date parsing: reject impossible calendar input

Last updated: 29 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

A DateTimeFormatter with STRICT resolution rejects invalid calendar combinations rather than adjusting them to a valid date.

Download Java source kit

This complete program targets Java 8. Its displayed output is checked by the tutorial validation script.

A parsed shape is not a valid date

A delivery request sends an ISO-shaped local date. Four digits, a dash and two numeric fields are insufficient: 29 February must be checked against the selected year. The fixture accepts the leap-year date and rejects the same day in a non-leap year. That distinction belongs at the request boundary.

Use uuuu for a proleptic year in this formatter. yyyy denotes year-of-era and can need an era to resolve under strict rules. A convenient formatter that normalizes an impossible day can move a booking away from the value a person submitted.

Dates do not contain deadlines

A LocalDate has no time or offset. Converting it to a deadline requires a zone and a rule for which instant ends the allowed period. Zone gaps and overlaps are separate from calendar validity, and a valid local date does not resolve them.

The immutable formatter can be reused. Do not replace it with a shared mutable legacy date parser. Exception messages may include user input; a public API should return a bounded error contract rather than exposing its entire parsing exception. Problem details supplies that response boundary.

Working program

Java
import java.time.LocalDate;
import java.time.format.*;
import java.util.Locale;
public class DeliveryDateInput {
    static final DateTimeFormatter INPUT = DateTimeFormatter.ofPattern("uuuu-MM-dd", Locale.ROOT)
        .withResolverStyle(ResolverStyle.STRICT);
    public static void main(String[] args) {
        System.out.println(LocalDate.parse("2024-02-29", INPUT));
        try { LocalDate.parse("2023-02-29", INPUT); }
        catch (DateTimeParseException rejected) { System.out.println("invalid day rejected"); }
    }
}

Output

Output
2024-02-29
invalid day rejected

Costs and boundaries

Parsing takes time proportional to the bounded input length and returns one date object. The formatter can be shared because it is immutable. This program does not test time-zone conversion or a database date column.

Common Mistakes

  • Do not silently repair a booking date.
  • Use the year field that matches the intended resolution contract.
  • A valid LocalDate is not an absolute instant.

Read next

Java date and time: local schedules versus instants, Java daylight-saving transitions: reject gaps and choose overlaps, Spring MVC ProblemDetail: stable errors without leaking internals.

java
strict-date-parsing
Storage details