开发中常遇到 java.text.ParseException: Unparseable date 异常,典型堆栈如下:
java.text.ParseException: Unparseable date: "6/1/2015 14:23:05"
at java.text.DateFormat.parse(DateFormat.java:357)
at com.example.controller.CpsController.toCpsLists(CpsController.java:126)
...
核心问题在于 输入日期格式与解析模式不匹配。异常信息明确显示输入为 "6/1/2015 14:23:05"(M/d/yyyy 格式),但代码使用 yyyy-MM-dd HH:mm:ss 进行解析。此外,代码存在冗余的三层转换:
Date startTime = dateFormat.parse(
dateFormat.format(
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(min)
)
);
这种 parse → format → parse 的往返转换不仅低效,还引入额外格式化风险。
SimpleDateFormat inputFormat = new SimpleDateFormat("M/d/yyyy HH:mm:ss");
Date date = inputFormat.parse(min); // 直接解析原始字符串
SimpleDateFormat inputFormat = new SimpleDateFormat("M/d/yyyy HH:mm:ss");
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = inputFormat.parse(min);
String formatted = outputFormat.format(date); // 仅在需要字符串输出时格式化
SimpleDateFormat 非线程安全,多线程环境下应使用 ThreadLocal 或 Java 8+ 的 DateTimeFormatterParseException 并记录原始输入,便于排查Date 或 LocalDateTime 对象,仅在序列化/展示时格式化DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/yyyy HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(min, formatter);
// 后续操作直接使用 dateTime 对象