11

Below is my code to parse the date using SimpleDateFormat with pattern:

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. 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

When I pass the same format like 2030-05-21 it works fine.

Can you guys please let me know how can I prevent such things in my code?

royhowie
  • 11,075
  • 14
  • 50
  • 67
Bhavesh Shah
  • 3,299
  • 11
  • 49
  • 73

2 Answers2

20

Basically you want SimpleDateFormat to be strict, so set lenient to false.

SimpleDateFormat format = new SimpleDateFormat(pattern);
format.setLenient(false);
dogant
  • 1,376
  • 1
  • 10
  • 23
  • Sadly setting lenient false is still lenient. "2010/01/5" is allowed for the pattern "yyyy/MM/dd". 20100901andGarbage" is allowed for the pattern "yyyyMMdd". I have made an extension of SimpleDateFormat that is strict here: http://stackoverflow.com/questions/16014488/simpledateformat-parse-ignores-the-number-of-characters-in-pattern/19503019#19503019 – Steve Zobell Feb 05 '16 at 20:31
4

If you can afford using Java 8 time API, its formatter works as expected:

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)
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334