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.
Code
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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.