当 str = 2011/12/12aaaaaaaaa 时 SimpleDateFormat parse(string str) 不会抛出异常?
下面是一个示例:
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 不是有效的日期字符串。但是该函数打印“Mon Dec 12 00:00:00 PST 2011”并且不会抛出 ParseException。
谁能告诉我如何让 SimpleDateFormat 将“2011/12/12aaa”视为无效日期字符串并引发异常?
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/12aaa is not a valid date string. However the function prints "Mon Dec 12 00:00:00 PST 2011" and ParseException isn't thrown.
Can anyone tell me how to let SimpleDateFormat treat "2011/12/12aaa" as an invalid date string and throw an exception?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
关于
parse(...)
的 JavaDoc 声明如下:似乎您无法使
SimpleDateFormat
抛出异常,但您可以执行以下操作:基本上,您检查解析是否消耗了整个字符串,如果不是,则输入无效。
The JavaDoc on
parse(...)
states the following:It seems like you can't make
SimpleDateFormat
throw an exception, but you can do the following:Basically, you check whether the parse consumed the entire string and if not you have invalid input.
检查日期是否有效
如果日期有效,以下方法将返回,否则将返回 false。
看看下面的类,它可以检查日期是否有效
**示例示例**
To chack whether a date is valid
The following method returns if the date is in valid otherwise it will return false.
Have a look on the following class which can check whether the date is valid or not
** Sample Example**
可以使用 Java 8 LocalDate:
如果输入参数为
"2011/12/12aaaaaaaaa"
,则输出为false
;如果输入参数为
"2011/12/12"
,则输出为true
Java 8 LocalDate may be used:
If input argument is
"2011/12/12aaaaaaaaa"
, output isfalse
;If input argument is
"2011/12/12"
, output istrue
成功解析整个模式字符串后,
SimpleDateFormat
停止评估要解析的数据。After it successfully parsed the entire pattern string
SimpleDateFormat
stops evaluating the data it was given to parse.查看方法文档,其中显示:
如果无法解析指定字符串的开头,则出现 ParseException
。带有javadoc的方法源代码:
Take a look on the method documentation which says:
ParseException if the beginning of the specified string cannot be parsed
.Method source code with javadoc:
您可以使用
ParsePosition
类或sdf.setLenient(false)
函数文档:
http://docs.oracle.com/javase/7 /docs/api/java/text/ParsePosition.html
http://docs.oracle .com/javase/7/docs/api/java/text/DateFormat.html#setLenient(boolean)
You can use the
ParsePosition
class or thesdf.setLenient(false)
functionDocs:
http://docs.oracle.com/javase/7/docs/api/java/text/ParsePosition.html
http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#setLenient(boolean)
只需设置 sdf.setLenient(false) 即可解决问题。
Simply setting
sdf.setLenient(false)
will do the trick..