繁体   English   中英

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

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

下面是我使用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();
}

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

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

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

基本上你希望SimpleDateFormat是严格的,所以将lenient设置为false。

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

如果您能负担得起使用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();
}

输出:

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