• 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

setLenient is not working in SimpleDateFormat

 
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Hi All,

I could not figure out what wrong here. even i set lenient is false. still SimpleDateFormat instance is parsing the wrong date.

Could any one please help me out???

public class DateValidation1 {

public static void main(String[] args) {
try {

SimpleDateFormat sdf = new SimpleDateFormat () ;
sdf.applyPattern("dd/MM/yyyy") ;
sdf.setLenient(false) ;
Date formattedDate = sdf.parse("02/06/2011hcdlkjlk");
System.out.println(formattedDate) ;

} catch (ParseException e) {
System.out.println (e.getMessage()) ;
e.printStackTrace();
}
}

}
 
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I don't see any problem with that code. The parsed date is June 2nd 2011 as expected.

I think you assume that the "hcdlkjlk" should cause the date parsing to fail. However, this has never been the case. The date parsing will continue until the desired pattern has been met; anything after that is ignored.

To get the kind of date parsing you want you should switch to the "other" parse method - the one that takes a ParsePosition argument:
 
Rob Spoor
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
And for your information, setLenient only determines whether or not dates like "31/02/2012" or "31/13/2012" are allowed. If the date format is lenient, this will cause the parsed date to be March 2nd 2012 / January 31st 2013. If the date format isn't lenient parsing will fail.
 
Never trust an airline that limits their passengers to one carry on iguana. Put this tiny ad in your shoe:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic