如何在将不正确的字符串解析为日期时获得异常或任何类型的反馈

How to get an exception or any sort of feedback while parsing incorrect String to Date

我想将 String 解析为 Date。问题是,如果我解析错误的日期,如 "2009-02-40",我不会得到任何异常(没有反馈说我传递了错误的日期),而是我将 Date 对象设置为 "2009-01-01"

 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
        try {
            Date result =  df.parse("2009-02-40");
            System.out.println(result);
        } catch (ParseException e) {
            e.printStackTrace();
        }  

当我像上面这样传递错误 Date 时如何获得异常?

您想在格式化程序上调用 setLenient(false)。这会导致 "strict" 检查何时进行解析。默认情况下,"lenient" 是 "true; and then some heuristics are used that turn " 垃圾 in" into whatever.

可能不是世界上最好的设计;但这就是它的工作原理。

df.parse("2009-02-40");如果无法解析指定字符串的开头,将抛出 ParseException。

对于严格解析,使用 df.setLenient(false);

试试下面的代码:

 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
         df.setLenient(false); //note the change here
            try {
                Date result =  df.parse("2009-02-40");
                System.out.println(result);
            } catch (ParseException e) {
                e.printStackTrace();
            }