Date with SimpleDateFormat in Java

The following code tries to parse a date 31-Feb-2013 13:02:23

with a given format.

DateFormat dateFormat=new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
System.out.println(dateFormat.parse("31-Feb-2013 13:02:23"));

      

Returns Sun Mar 03 13:02:23 IST 2013

.

I need to invalidate dates like this with an invalid date. This (etc.) Date should not be analyzed (or should be invalidated in some other way). Is it possible?

+3


source to share


2 answers


Use DateFormat.setLenient(boolean)

with an argument false

:



DateFormat dateFormat=new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
dateFormat.setLenient(false);
System.out.println(dateFormat.parse("31-Feb-2013 13:02:23"));

      

+4


source


Java date calculation is soft. In soft analysis, the parser can use heuristics to interpret inputs that do not exactly correspond to this object.

You have to pass false for lenient to dateformat, which goes into Strict mode . For rigorous parsing, the input must match this object.



DateFormat dateFormat=new SimpleDateFormat("...");
dateFormat.setLenient(false); // turn on Strict mode
dateFormat.parse("31-Feb-2013 13:02:23");// throws java.text.ParseException 

      

+4


source







All Articles