Date with SimpleDateFormat in Java

谁说我不能喝 提交于 2019-12-10 21:38:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!