SimpleDateFormat.parse() - 为不同的日期格式生成错误的日期

Bha*_*hah 7 java date

下面是我使用SimpleDateFormat模式解析日期的代码:

String pattern = "yyyy-MM-dd";    
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
    Date date = format.parse("05-21-2030");
    System.out.println(date);
} catch (ParseException e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

您可以看到我传递给解析的日期与SimpleDateFormat中指定的日期格式不同.在这种情况下,由于格式不同,我希望有一种解雇,但它使用一些不同的日期值成功解析.我得到了输出 - Tue Mar 22 00:00:00 IST 12

当我传递相同的格式,如2030-05-21,它工作正常.

你能告诉我如何在我的代码中阻止这些事情吗?

dog*_*ant 14

基本上你想要SimpleDateFormat严格,所以将lenient设置为false.

SimpleDateFormat format = new SimpleDateFormat(pattern);
format.setLenient(false);
Run Code Online (Sandbox Code Playgroud)