DateTimeFormatter ResolverStyle Strict Parsing

The same impossible date resolves three ways: SMART clamps to month end, STRICT rejects outright, LENIENT overflows — pick the policy per input surface.

JavaForm Validation

Code

snippet
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.ResolverStyle;

public class DateInputGate {

    public static void main(String[] args) {
        String input = "2026-02-30"; // 2026 不是闰年,2 月没有 30 日

        // SMART(默认):超出月末的日子收敛到当月最后一天
        DateTimeFormatter smart = DateTimeFormatter
                .ofPattern("uuuu-MM-dd")
                .withResolverStyle(ResolverStyle.SMART);
        System.out.println("smart   -> " + LocalDate.parse(input, smart));

        // STRICT:不存在的日期直接拒绝解析
        DateTimeFormatter strict = DateTimeFormatter
                .ofPattern("uuuu-MM-dd")
                .withResolverStyle(ResolverStyle.STRICT);
        try {
            LocalDate.parse(input, strict);
        } catch (Exception rejected) {
            System.out.println("strict  -> rejected: " + rejected.getMessage());
        }

        // LENIENT:不纠正,溢出直接进位
        DateTimeFormatter lenient = DateTimeFormatter
                .ofPattern("uuuu-MM-dd")
                .withResolverStyle(ResolverStyle.LENIENT);
        System.out.println("lenient -> " + LocalDate.parse(input, lenient));

        // STRICT 下 pattern 必须写 uuuu:yyyy 是 year-of-era,还要求 era 字段才能解析
    }
}

How it works

DateTimeFormatter ResolverStyle Strict Parsing reduces to the class DateInputGate and the function main.

Using it

The demo output is labeled (smart ->, strict -> rejected:, lenient ->), so every printed line maps back to its originating operation.

Key statements

String input = "2026-02-30"; // 2026 不是闰年,2 月没有 30 日
// SMART(默认):超出月末的日子收敛到当月最后一天
DateTimeFormatter smart = DateTimeFormatter
        .ofPattern("uuuu-MM-dd")
        .withResolverStyle(ResolverStyle.SMART);
DateTimeFormatter lenient = DateTimeFormatter
        .ofPattern("uuuu-MM-dd")
        .withResolverStyle(ResolverStyle.LENIENT);
DateTimeFormatter strict = DateTimeFormatter
        .ofPattern("uuuu-MM-dd")
        .withResolverStyle(ResolverStyle.STRICT);

Interactive Tools for This Topic

FAQ

What does DateTimeFormatter ResolverStyle Strict Parsing print when run?
Invoke the file as-is — the `smart ->`, `strict -> rejected:`, `lenient ->` prefixes identify which step printed each line.