4

This question is raised by the following code:

DateFormat DF = new SimpleDateFormat("yyyyMMdd");
String dateString = "20110133";
System.out.println(DF.parse(dateString));
// Wed Feb 02 00:00:00 CET 2011

The parse method transformed Jan 33 to Feb 02. Is there a way to throw an Exception if the dateString does not represent a real date?

Just like DateTime.ParseExact in .NET.

Zeemee
  • 10,156
  • 13
  • 50
  • 79

2 Answers2

9

Try doing this

DF.setLenient(false);

javadoc reference

Bala R
  • 104,615
  • 23
  • 192
  • 207
  • It's not perfect and won't work in all instances, see https://stackoverflow.com/questions/13088140/java-how-to-parse-a-date-strictly – rboy Jul 31 '18 at 19:16
4

You can use the setLenient(boolean) method of the DateFormat class to tell it not to be lenient (i.e. accept and then convert) with dates that aren't valid.

Anthony Grist
  • 37,856
  • 8
  • 63
  • 74
  • Will not always work, see this https://stackoverflow.com/questions/13088140/java-how-to-parse-a-date-strictly – rboy Jul 31 '18 at 19:17