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

Java设置法国Locale的DateTimeFormatter解析四月日期报错如何解决

问题根因

你的日期匹配模式和输入的月份格式不匹配,具体原因如下:

  • 模式中使用的MMM代表对应区域语言的月份短名称(缩写),你给出的可正常解析的示例19 déc. 2019 (21:15)、10 févr. 2020 (07:58)里的déc.、févr.都是法语月份的标准缩写。
  • 法语中六月(juin)的缩写和全称完全一致,所以用MMM模式也能正常匹配六月的日期;但四月的缩写是avr.,你输入的avril是四月的完整名称,对应模式应该是MMMM,因此解析失败。

解决方案

方案1:修改模式匹配月份全称

如果你的输入日期统一使用月份全称,直接把模式里的MMM改为MMMM即可:

Locale locale = Locale.FRANCE;
DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
        .appendPattern("dd MMMM yyyy (HH:mm)")
        .toFormatter(locale);
// 测试四月日期可正常解析
LocalDateTime dateTime1 = LocalDateTime.parse("01 avril 2021 (09:40)", dateTimeFormatter);

方案2:兼容缩写、全称两种月份格式

如果你的输入里同时存在缩写和全称的月份格式,可以通过appendOptional添加两种匹配规则,配合宽松解析提高兼容性:

Locale locale = Locale.FRANCE;
DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
        .appendPattern("dd ")
        // 同时支持长/短月份名匹配
        .optionalStart().appendPattern("MMMM").optionalEnd()
        .optionalStart().appendPattern("MMM").optionalEnd()
        .appendPattern(" yyyy (HH:mm)")
        .parseLenient()
        .toFormatter(locale);

修改后两种格式的日期都可以正常解析。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 17:36:02