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
相关产品推荐
相关产品推荐

