2

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.

Arn
  • 25
  • 1
  • 3
  • [The JavaDocs of `SimpleDateFormat`](https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html#parse(java.lang.String,%20java.text.ParsePosition)) state *parsing does not necessarily use all characters up to the end of the string*. I think that's the reason for this behaviour. – deHaar Sep 27 '21 at 08:43
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Sep 27 '21 at 18:37

1 Answers1

6

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.

MC Emperor
  • 22,334
  • 15
  • 80
  • 130