Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a DateFormat parse an exact date in java (like DateTime.ParseExact in .NET)?

Tags:

java

date

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.

like image 681
Zeemee Avatar asked Dec 10 '22 07:12

Zeemee


2 Answers

Try doing this

DF.setLenient(false);

javadoc reference

like image 187
Bala R Avatar answered Dec 11 '22 20:12

Bala R


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.

like image 30
Anthony Grist Avatar answered Dec 11 '22 19:12

Anthony Grist