Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error parsing String to Date in Java

Tags:

java

date

parsing

Yes, another Java Date post :)

My problem:

simple standard code, used for test if an inserted date is in the requested form (dd/MM/yyyy):

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try {

   sdf.parse(strDate); 

} catch(ParseException e) {

   // err

}

strDate = "10-12-2012" ----> sysout = err (ok)

strDate = "2012-11-10" ----> sysout = err (ok)

strDate = "15/10/2011" ----> sysout = parse (ok)

the problem:

strDate = "2012/12/15" ----> sysout = this date that i expect an error result parsed like "Tue Jun 03 00:00:00 CET 21"

Who knows???

like image 289
Salvatore D'alessandro Avatar asked Nov 23 '12 14:11

Salvatore D'alessandro


1 Answers

just set setLenient to false.

FROM API :

setLenient method:

Specify whether or not date/time parsing is to be lenient. With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object's format. With strict parsing, inputs must match this object's format.

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try {
  sdf.setLenient(false);
  System.out.println(sdf.parse("2012/12/15")); 
} catch(ParseException e) {
  e.printStackTrace();
}
like image 100
PermGenError Avatar answered Sep 24 '22 15:09

PermGenError