Reputation: 2080
The following code...
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
df.setLenient(false);
Date date = df.parse("2012115");
...parses the string "2012115"
to the Date equivalent of November 5th, 2012. I want it to fail parsing, because it is missing one day character. In other words, I only want the string "20121105"
to evaluate to that date. Is there a way to enforce this, other than evaluating the length of the string?
Upvotes: 2
Views: 988
Reputation: 34387
...parses the string "2012115" to the Date equivalent of November 5th, 2012. I want it to fail parsing, because it is missing one day character. In other words, I only want the string "20121105" to evaluate to that date.
I doubt you could do it using the formatter only. As a workaround, you may want to put a check on the date string length before parsing as below:
String dateString = "2012115";
String formatString = "yyyyMMdd";
if(dateString == null || dateString.length() != formatString.length()){
throw new ParseException("Invalid Date Input", 0);
}
SimpleDateFormat formatter= new SimpleDateFormat(formatString);
formatter.setLenient(false);
Date date = df.parse(dateString);
Upvotes: 1
Reputation: 4650
You could actually format it again and check if they are the same
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
df.setLenient(false);
String dstr = "2012115";
Date date = df.parse(dstr);
String newdstr = df.format (date);
if (!newdstr.equals(dstr)) {
throw new ParseException ("bla bla");
}
Upvotes: 1