Search code examples
javasimpledateformat

Java SimpleDateFormat accepts invalid date. with format 'MM/dd/yyyy' parses '01/01/2021anything'


I'm trying to parse a string date value to date object. If the provided date is not in the correct format, error has to be thrown. Trying to achieve this with SimpleDateFormat, but Its not working as expected.

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
sdf.setLenient(false);
Date d = sdf.parse("01/01/2021anything");
System.out.println(d);

For the above code getting output Fri Jan 01 00:00:00 GMT 2021 where I expected ParseException. Can someone explain why this happens and how I can validate the above date with SimpleDateFormat. Appreciate the effort.


Solution

  • This happens because it is implemented this way.

    SimpleDateFormat will inspect the format, and start to parse each token present in the format, but does not necessarily parse the whole string, according to the docs:

    Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string.

    You shouldn't be using SimpleDateFormat and Date anyways, because they have more problems than this one.

    Use classes from the java.time package instead. In your case, you should probably be using LocalDate. A simple translation of your code to code using java.time would be something like this:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
    LocalDate d = LocalDate.parse("01/01/2021anything", formatter);
    System.out.println(d);
    

    The abovementioned code will throw a DateTimeParseException, because it doesn't like anything.