You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java中解析德语自定义格式日期并处理缩写点问题

解决德语日期解析异常与格式化多余句点问题

问题根源

JDK 11中Locale.GERMAN对应的月份缩写默认带句点(如Jan.、Okt.),但你要解析的日期是不带句点的缩写(如Aug、Mai),格式器无法匹配所以抛出DateTimeParseException;同时默认格式化逻辑也会输出带句点的缩写,导致出现多余的点。

解决方案:自定义德语月份缩写映射

通过DateTimeFormatterBuilder配置自定义的不带句点的德语月份缩写,覆盖默认规则,同时开启大小写不敏感解析(适配输入中首字母大写的缩写)。

完整代码示例

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class GermanDateHandler {
    // 定义不带句点的德语月份缩写映射
    private static final Map<Long, String> GERMAN_MONTH_ABBREVIATIONS = new HashMap<>();

    static {
        GERMAN_MONTH_ABBREVIATIONS.put(1L, "Jan");
        GERMAN_MONTH_ABBREVIATIONS.put(2L, "Feb");
        GERMAN_MONTH_ABBREVIATIONS.put(3L, "Mär");
        GERMAN_MONTH_ABBREVIATIONS.put(4L, "Apr");
        GERMAN_MONTH_ABBREVIATIONS.put(5L, "Mai");
        GERMAN_MONTH_ABBREVIATIONS.put(6L, "Jun");
        GERMAN_MONTH_ABBREVIATIONS.put(7L, "Jul");
        GERMAN_MONTH_ABBREVIATIONS.put(8L, "Aug");
        GERMAN_MONTH_ABBREVIATIONS.put(9L, "Sep");
        GERMAN_MONTH_ABBREVIATIONS.put(10L, "Okt");
        GERMAN_MONTH_ABBREVIATIONS.put(11L, "Nov");
        GERMAN_MONTH_ABBREVIATIONS.put(12L, "Dez");
    }

    public static void main(String[] args) {
        // 构建自定义格式器
        DateTimeFormatter germanDateFormatter = new DateTimeFormatterBuilder()
                .appendPattern("dd-")
                // 绑定自定义月份缩写映射
                .appendText(ChronoField.MONTH_OF_YEAR, GERMAN_MONTH_ABBREVIATIONS)
                .appendPattern("-yyyy")
                // 开启大小写不敏感解析(适配输入中首字母大写的情况)
                .parseCaseInsensitive()
                .toFormatter(Locale.GERMAN);

        // 测试解析不带句点的日期
        LocalDate parsedDate = LocalDate.parse("15-Aug-2023", germanDateFormatter);
        System.out.println("解析结果:" + parsedDate); // 输出:2023-08-15

        // 测试格式化(输出不带句点的缩写)
        String formattedDate = parsedDate.format(germanDateFormatter);
        System.out.println("格式化结果:" + formattedDate); // 输出:15-Aug-2023

        // 测试另一个日期
        LocalDate anotherDate = LocalDate.parse("30-Mai-2024", germanDateFormatter);
        System.out.println("另一解析结果:" + anotherDate); // 输出:2024-05-30
        System.out.println("另一格式化结果:" + anotherDate.format(germanDateFormatter)); // 输出:30-Mai-2024
    }
}

关键说明

  1. 自定义月份映射:直接指定每个月份对应的不带句点缩写,确保解析和格式化的一致性。注意三月的缩写是Mär,包含德语变音符号,需确保代码文件编码为UTF-8避免乱码。
  2. 大小写不敏感解析:通过parseCaseInsensitive()方法,兼容输入中首字母大写(如Aug)或全小写(如aug)的缩写形式。
  3. 格式器构建逻辑:拆分dd-MMM-yyyy模式,用appendText()绑定自定义映射,替代默认的月份解析/格式化规则。

内容的提问来源于stack exchange,提问作者MS13

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 20:38:34