Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

ResolverStyle — strict date resolution

ResolverStyle controls how parsed fields become a date or time. The behavior of ResolverStyle.STRICT depends on the fields: for an ISO calendar date given as year, month, and day, it rejects February 29 in a non-leap year.

Version: Java SE 21 (documentation scope); repository and production runtimes not attested

Syntax

DateTimeFormatter.ofPattern("uuuu-MM-dd", Locale.ROOT).withResolverStyle(ResolverStyle.STRICT)

ResolverStyle is an enum in java.time.format. Parsing first reads fields from text, then combines them into a date or time. The style controls that second phase, not the initial matching of text against a pattern or the formatting of output.

When resolving an ISO calendar date from year, month, and day, ResolverStyle.STRICT requires the day to exist in the specified month and year. For those same fields, ResolverStyle.SMART can replace a day number that is too large with the last day of the month, while ResolverStyle.LENIENT allows overflow between fields. The rules depend on the fields being resolved. For example, in Java SE 21, when resolving a week-based date, localized WeekFields can resolve week 53 to week 52 in a 52-week week-based year, even in STRICT mode.

Set the style with withResolverStyle(ResolverStyle.STRICT) and retain the returned formatter: the method does not modify the original. A formatter created with ofPattern defaults to SMART. For a date pattern without an era, use uuuu-MM-dd: uuuu means year, whereas yyyy means year-of-era, which may be insufficient to produce a LocalDate under strict resolution without an era.

The example accepts 2024-02-29 but catches DateTimeParseException for 2023-02-29. It prints a fixed message rather than implementation-dependent exception text. Documentation scope: Java SE 21; repository and production runtimes have not been attested.

Examples

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.format.ResolverStyle;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter
                .ofPattern("uuuu-MM-dd", Locale.ROOT)
                .withResolverStyle(ResolverStyle.STRICT);

        for (String text : new String[] {"2024-02-29", "2023-02-29"}) {
            try {
                System.out.println(LocalDate.parse(text, formatter));
            } catch (DateTimeParseException ex) {
                System.out.println("Rejected: " + text);
            }
        }
    }
}

Result

2024-02-29
Rejected: 2023-02-29

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources