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

SimpleDateFormat使用ddMMyyyy模式解析月份与年份出错问题求助

解决SimpleDateFormat自动转换非法日期的问题

SimpleDateFormat默认处于宽松解析模式(lenient),会自动将超出合法范围的日期分量转换为有效日期。比如你输入的"22221985"中,"22"作为月份会被解析成1年零10个月,叠加到原年份1985上,最终得到1986年10月22日。

要实现非法日期分量抛出异常的需求,只需关闭宽松模式:

SimpleDateFormat formatter = new SimpleDateFormat("ddMMyyyy");
formatter.setLenient(false); // 关闭宽松解析
try {
  Date date = formatter.parse("22221985");
} catch (ParseException e) {
  // 此时会抛出ParseException,符合预期
  e.printStackTrace();
}

额外建议:SimpleDateFormat存在线程不安全问题,Java 8及以上版本推荐使用java.time包下的DateTimeFormatter,它天生线程安全且默认是严格解析模式:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyy");
try {
  LocalDate date = LocalDate.parse("22221985", formatter);
} catch (DateTimeParseException e) {
  // 直接抛出异常,无需额外配置
  e.printStackTrace();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 14:30:58