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

使用M/d/yyyy, h:mm a格式解析LocalDateTime时索引17解析失败

问题原因与解决方案

索引17的解析问题根源

索引17对应字符串里的p字符(即pm的首字母),解析失败的核心原因是DateTimeFormatter默认使用JVM的系统默认Locale。如果你的默认Locale不是英文(比如中文),Formatter无法识别英文的am/pm标识,导致匹配失败。

Java的DateTimeFormatter处理a模式符(表示AM/PM标记)时,会依赖Locale定义的对应文本。非英文Locale下,AM/PM的标记文本不是am/pm,自然无法匹配解析。

修复方法

给DateTimeFormatter指定英文Locale即可解决问题,修改后的代码如下:

@Test
public void testLocalDateTime_shortDateTimePattern() {
    String pattern = "M/d/yyyy, h:mm a";
    System.out.println(pattern);
    // 指定英文Locale,确保能识别am/pm标识
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.US);

    String dateString = "12/16/2022, 1:33 pm";
    System.out.println(dateString);

    LocalDateTime result = LocalDateTime.parse(dateString, formatter);
    System.out.println(result);
}

补充说明

如果应用需要适配多Locale场景,可以根据需求动态切换Locale;如果固定使用英文时间格式,直接绑定英文Locale是最稳妥的处理方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 08:55:23