Error parsing String to Date in Java

date, java, parsing

Solution

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();
}

Problem

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???

Original source