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

Java用dd.MM.yyyy HH:mm解析日期抛出DateTimeParseException异常

Java日期解析异常排查方案

异常原因

你使用的DateTimeFormatter模式dd.MM.yyyy HH:mm中,HH要求待解析字符串的小时部分必须是2位数字,而你提供的待解析文本01.03.2021 0:01的小时仅为1位0,和模式规则不匹配,因此在小时起始的索引11位置抛出解析异常。

解决方案

  • 修改日期模式,将双位HH替换为单位H,H支持匹配1位或2位的24小时制小时值,适配当前输入格式,修改后的代码如下:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy H:mm");
String filterValue = "01.03.2021 0:01";
LocalDateTime parsedDate = LocalDateTime.parse(filterValue, formatter);
  • 若业务场景中还存在分钟仅为1位的输入,可进一步将模式调整为dd.MM.yyyy H:m,可同时兼容1位或2位的小时、分钟输入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 15:27:03