• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Issue with SimpleDateFormat

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Than you Agador for your speedy response. That did work.

Thanks again.
reply
    Bookmark Topic Watch Topic
  • New Topic