← 中文资源

简体中文版本

DateTimeFormatter 三种解析口径

同一个 2026-02-30 三种口径:SMART 收敛到当月最后一天,STRICT 直接拒绝,LENIENT 进位到 3 月;STRICT 的 pattern 必须用 uuuu 而不是 yyyy。

阅读英文原文

实现说明

底层就是类 DateInputGate和函数 main。

使用要点

  • 直接运行文件,输出会带上标签,比如 smart ->、strict -> rejected:、lenient ->——输出的每一行都能指回产生它的那次调用。

常见问题

运行「DateTimeFormatter 三种解析口径」会打印什么?

整个文件跑完,输出行以 smart ->、strict -> rejected:、lenient -> 这类前缀开头。

核心语句

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);

代码示例

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 字段才能解析
    }
}