这里是一个例子:
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/12aaa不是有效的日期字符串.但是,该函数将打印"PST 2011 Mon Dec 12 00:00:00 PST 2011",并且不会引发ParseException.
2011/12/12aaa is not a valid date string. However the function prints "Mon Dec 12 00:00:00 PST 2011" and ParseException isn't thrown.
有人可以告诉我如何让SimpleDateFormat将"2011/12/12aaa"视为无效的日期字符串并引发异常吗?
Can anyone tell me how to let SimpleDateFormat treat "2011/12/12aaa" as an invalid date string and throw an exception?
推荐答案parse(...)上的JavaDoc声明以下内容:
The JavaDoc on parse(...) states the following:
解析并不一定要使用直到字符串末尾的所有字符
parsing does not necessarily use all characters up to the end of the string
似乎您无法使SimpleDateFormat引发异常,但是您可以执行以下操作:
It seems like you can't 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 parse consumed the entire string and if not you have invalid input.
更多推荐
当str = 2011/12/12aaaaaaaaaaa时,SimpleDateFormat parse(string str)不会引发异常?
发布评论