• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Issue with SimpleDateFormat

 
Sharma Vedula
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to use the SimpleDateFormat class to validate a date entered by a user in a web app. Unfortunately, when I test it by putting an invalid date or month, it still computes the date and returns it as a valid date. Here is a test code to prove my point:

public static void main(String[] args) {
//String pattern = "dd/MM/yyyy";
String pattern = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date nDate;
String value = "100/26/2006";
System.out.println("**************DATE: " + value);
try {
nDate = sdf.parse(value);
System.out.println("************DATE AFTER PARSING: " + nDate);
} catch (ParseException ex) {
System.out.println(ex);
ex.printStackTrace();
}
}

Can somebody point me the mistake I am making? I was expecting an exception to be thrown.

Thanks
 
Agador Paloi
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you need :

sdf.setLenient(false);


to throw a parse exception for invalid date
 
Sharma Vedula
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Than you Agador for your speedy response. That did work.

Thanks again.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic