← 中文资源

简体中文版本

大小写无关的月份解析

默认的 DateTimeFormatter 区分大小写,jan 无法通过 MMM 模式;用 parseCaseInsensitive 构建的 formatter 对 jan、JAN、Jan 一视同仁。

阅读英文原文

实现说明

活动部件是类 MonthNameCase和函数 main。

使用要点

  • 每一步打印都带着自己的标签:strict accepted lowercase: unexpected、strict rejected lowercase month、jan ->。

常见问题

运行「大小写无关的月份解析」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 strict accepted lowercase: unexpected、strict rejected lowercase month、jan -> 这类标签。

核心语句

DateTimeFormatter strict = DateTimeFormatter.ofPattern("uuuu-MMM-dd", Locale.ENGLISH);
DateTimeFormatter lenient = new DateTimeFormatterBuilder()
        .parseCaseInsensitive()
        .appendPattern("uuuu-MMM-dd")
        .toFormatter(Locale.ENGLISH);
LocalDate.parse("2026-jan-07", strict);

代码示例

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

public class MonthNameCase {

    public static void main(String[] args) {
        DateTimeFormatter strict = DateTimeFormatter.ofPattern("uuuu-MMM-dd", Locale.ENGLISH);
        try {
            LocalDate.parse("2026-jan-07", strict);
            System.out.println("strict accepted lowercase: unexpected");
        } catch (DateTimeParseException rejected) {
            System.out.println("strict rejected lowercase month");
        }

        DateTimeFormatter lenient = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .appendPattern("uuuu-MMM-dd")
                .toFormatter(Locale.ENGLISH);

        System.out.println("jan -> " + LocalDate.parse("2026-jan-07", lenient));
        System.out.println("JAN -> " + LocalDate.parse("2026-JAN-07", lenient));
        System.out.println("Jan -> " + LocalDate.parse("2026-Jan-07", lenient));
    }
}