问题
The following code attempts 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"));
It returns Sun Mar 03 13:02:23 IST 2013
.
I need to invalidate such dates indicating invalid date. This (and so forth) date shouldn't be parsed (or should be invalidated in any other way). Is this possible?
回答1:
Use DateFormat.setLenient(boolean) method with false
argument:
DateFormat dateFormat=new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
dateFormat.setLenient(false);
System.out.println(dateFormat.parse("31-Feb-2013 13:02:23"));
回答2:
Java Date calculation is lenient. With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object's format.
You must pass false to lenient to dateformat which truns to Strict mode. With strict parsing, inputs must match this object's format.
DateFormat dateFormat=new SimpleDateFormat("...");
dateFormat.setLenient(false); // turn on Strict mode
dateFormat.parse("31-Feb-2013 13:02:23");// throws java.text.ParseException
来源:https://stackoverflow.com/questions/14786257/date-with-simpledateformat-in-java