This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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: 19651
    
  18

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: 19651
    
  18

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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: setLenient is not working in SimpleDateFormat
 
Similar Threads
Gregorian Calandar
Populating select box with dates
Code review required for converting dateformat
How to get tomorrow's date?
Calendar problem