aspose file tools*
The moose likes Java in General and the fly likes Issue with SimpleDateFormat Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Issue with SimpleDateFormat" Watch "Issue with SimpleDateFormat" New topic
Author

Issue with SimpleDateFormat

Sharma Vedula
Greenhorn

Joined: May 02, 2007
Posts: 9
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

Joined: Jan 24, 2006
Posts: 118
I think you need :

sdf.setLenient(false);


to throw a parse exception for invalid date
Sharma Vedula
Greenhorn

Joined: May 02, 2007
Posts: 9
Than you Agador for your speedy response. That did work.

Thanks again.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Issue with SimpleDateFormat