简体   繁体   English

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

[英]SimpleDateFormat.parse() - generates wrong date for different date-formats

Below is my code to parse the date using SimpleDateFormat with pattern: 下面是我使用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();
}

You can see the date which I passed to parse is different from date format which is specified in SimpleDateFormat. 您可以看到我传递给解析的日期与SimpleDateFormat中指定的日期格式不同。 In this case I was expecting kind of excpetion as format is different but it parsed successfully with some different date values. 在这种情况下,由于格式不同,我希望有一种解雇,但它使用一些不同的日期值成功解析。 I got the output - Tue Mar 22 00:00:00 IST 12 我得到了输出 - Tue Mar 22 00:00:00 IST 12

When I pass the same format like 2030-05-21 it works fine. 当我传递相同的格式,如2030-05-21,它工作正常。

Can you guys please let me know how can I prevent such things in my code? 你能告诉我如何在我的代码中阻止这些事情吗?

Basically you want SimpleDateFormat to be strict, so set lenient to false. 基本上你希望SimpleDateFormat是严格的,所以将lenient设置为false。

SimpleDateFormat format = new SimpleDateFormat(pattern);
format.setLenient(false);

If you can afford using Java 8 time API, its formatter works as expected: 如果您能负担得起使用Java 8时间API,其格式化程序将按预期工作:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
try {
    LocalDate date = LocalDate.parse("2030-05-21", formatter);
    System.out.println(date);
    LocalDate date2 = LocalDate.parse("05-21-2030", formatter);
    System.out.println(date2);
} catch (DateTimeParseException e) {
    e.printStackTrace();
}

Output: 输出:

2030-05-21
java.time.format.DateTimeParseException: Text '05-21-2030' could not be parsed at index 0
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1947)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1849)
    at java.time.LocalDate.parse(LocalDate.java:400)
    at java8.Snippet.main(Snippet.java:25)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM