2015-05-15 49 views
6

下面是我的代码来解析使用的SimpleDateFormat与模式日期:SimpleDateFormat.parse() - 生成不同的日期格式错误的日期

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中指定。在这种情况下,由于格式不同,我期待有一些改变,但它用一些不同的日期值成功解析。我得到的输出 - 周二3月22日00:00:00北京时间12

当我传似2030年5月21日相同的格式,它工作正常。

你们可以请让我知道如何防止我的代码中的这样的事情?

+1

你必须使用在这种情况下HTTP严格:// stackoverflow.com/questions/13088140/java-how-to-parse-a-date-strictly –

+0

@NitinDandriyal:没有明确的严格模式。你必须关闭宽大处理。 – Brian

+0

我的意思是严格的作为一个通用术语,这就是为什么给出适当回答的链接 –

回答

13

基本上你想SimpleDateFormat是严格的,所以从宽松到假。

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

可悲的是,设置宽松的虚假仍然是宽松的。 “2010/01/5”可以用于“yyyy/MM/dd”模式。 20100901andGarbage“可以用于模式”yyyyMMdd“。我在这里对SimpleDateFormat进行了严格的扩展:http://stackoverflow.com/questions/16014488/simpledateformat-parse-ignores-the-number-of-characters-in -pattern/19503019#19503019 –

3

如果你能负担得起使用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)