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

使用相同格式化模式解析LocalDateTime时为何抛出DateTimeParseException?

问题原因与解决方案

核心问题

你的格式化模式MM-dd-yyyy hh:mm:ss:nn存在两个关键问题,其中12小时制小时未搭配AM/PM标识是导致解析失败的直接原因:

  • hh是12小时制的小时格式符,格式化时LocalDateTime本身携带明确的24小时制时间,所以能直接输出12小时制的数值;但解析时,字符串仅包含小时数(如10),没有说明是上午还是下午,解析器只能识别出HourOfAmPm=10,却无法将其转换为一天中具体的24小时制小时(0-23),因此无法构建LocalTime,最终抛出DateTimeParseException。
  • 额外说明:nn是纳秒的格式符(对应n),如果你的意图是表示毫秒,应该改用SSS(毫秒为三位,范围0-999),不过这不是解析失败的核心原因。

修复方案

方案一:改用24小时制小时格式

将hh替换为HH(24小时制小时格式符),同时按需调整纳秒/毫秒格式:

// 若要表示毫秒,用SSS;若需纳秒,保留nn即可
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-yyyy HH:mm:ss:SSS");
LocalDateTime dateTime = LocalDateTime.of(2023, 1, 12, 10, 2, 7, 0);
String formatted = formatter.format(dateTime);
System.out.println(formatted); // 输出:01-12-2023 10:02:07:000
LocalDateTime.parse(formatted, formatter); // 解析成功

方案二:保留12小时制并添加AM/PM标识

在模式中加入a(AM/PM标识),让格式化后的字符串携带上午/下午信息,解析时即可明确小时的上下文:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-yyyy hh:mm:ss:SSS a");
LocalDateTime dateTime = LocalDateTime.of(2023, 1, 12, 10, 2, 7, 0);
String formatted = formatter.format(dateTime);
System.out.println(formatted); // 输出:01-12-2023 10:02:07:000 上午
LocalDateTime.parse(formatted, formatter); // 解析成功

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 21:35:27