Java – simpledateformat parse (string STR) will not throw an exception when STR = 2011 / 12 / 12aaa?
•
Java
Here is an example:
public MyDate() throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d"); sdf.setLenient(false); String t1 = "2011/12/12aaa"; System.out.println(sdf.parse(t1)); }
2011 / 12 / 12 AAA is not a valid date string However, this function prints "00:00:00 PST, Monday, December 12, 2011" and will not throw parseexception
Anyone can tell me how to make simpledateformat treat "2011 / 12 / 12aaa" as an invalid date string and throw an exception?
Solution
The Javadoc in parsing (...) is described as follows:
It seems that you cannot make simpledateformat throw an exception, but you can do the following:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d"); sdf.setLenient(false); ParsePosition p = new ParsePosition( 0 ); String t1 = "2011/12/12aaa"; System.out.println(sdf.parse(t1,p)); if(p.getIndex() < t1.length()) { throw new ParseException( t1,p.getIndex() ); }
Basically, you check whether the analysis consumes the entire string, if not you have invalid input
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码