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

Java中SimpleDateFormat解析非指定格式日期出错求助

解决SimpleDateFormat宽松解析的问题

问题原因

SimpleDateFormat默认处于宽松解析模式,它会自动忽略输入字符串中不符合格式的字符(比如你例子里的横杠),强行尝试解析,因此不会抛出ParseException,反而得到错误的日期结果。

解决方案

调用SimpleDateFormat的setLenient(false)方法开启严格解析模式,当输入字符串与指定格式不匹配时,就会抛出ParseException。

修改后的代码示例

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
dateFormat.setLenient(false); // 开启严格解析模式
try {
    dateFormat.parse("20000611"); // 格式匹配,正常解析
    dateFormat.parse("2000-06-11"); // 格式不匹配,抛出ParseException
} catch (ParseException e) {
    e.printStackTrace();
}

更推荐的方案(Java 8及以上)

如果项目使用Java 8+版本,建议使用java.time包下的新日期时间API,DateTimeFormatter默认就是严格模式,类型更安全,同时避免了SimpleDateFormat的线程不安全问题。

代码示例

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class DateParseDemo {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        try {
            LocalDate date1 = LocalDate.parse("20000611", formatter); // 正常解析
            LocalDate date2 = LocalDate.parse("2000-06-11", formatter); // 格式不匹配,抛出DateTimeParseException
        } catch (DateTimeParseException e) {
            e.printStackTrace();
        }
    }
}

内容的提问来源于stack exchange,提问作者Keham Makene

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 19:52:08