wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes setLenient is not working in SimpleDateFormat Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "setLenient is not working in SimpleDateFormat" Watch "setLenient is not working in SimpleDateFormat" New topic
Author

setLenient is not working in SimpleDateFormat

prasad kakani
Ranch Hand

Joined: Jul 15, 2008
Posts: 59


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

Joined: Oct 27, 2005
Posts: 19682
    
  20

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:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19682
    
  20

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: setLenient is not working in SimpleDateFormat