Jorge Aranda
Jorge Aranda

Reputation: 2080

How to force dateFormat to take exactly the specified number of characters as valid?

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

Answers (2)

Yogendra Singh
Yogendra Singh

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

ShyJ
ShyJ

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

Related Questions