Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

setLenient is not working in SimpleDateFormat

 
prasad kakani
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • 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();
}
}

}
 
Rob Spoor
Sheriff
Pie
Posts: 20667
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • 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
Pie
Posts: 20667
65
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic