String to Date parsing error in Java

Yes, another Java Date :)

My problem:

simple standard code used to check if the 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 = "10/15/2011" ----> sysout = parse (ok)

problem:

strDate = "2012/12/15" ----> sysout = this date when I expect an error the result is parsed as "Tue Jun 03 00:00:00 CET 21"

Who knows???

+6
source share
1 answer

just set setLenient to false .

FROM API:

setLenient:

Specify whether to parse date and time parsing. With soft parsing, the analyzer can use heuristics to interpret inputs that do not exactly match this object. With strict parsing, Inputs must match this object.

 SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); try { sdf.setLenient(false); System.out.println(sdf.parse("2012/12/15")); } catch(ParseException e) { e.printStackTrace(); } 
+8
source

All Articles