我正在使用 MM-dd-yyyy HH:mm:ss
格式解析用户输入的日期字符串,我发现 12-20-2012 10:10:10 abcdexxxx
也可以通过。这怎么会发生?这是我的代码:
SimpleDateFormat df = new SimpleDateFormat( "MM-dd-yyyy HH:mm:ss" );
String currColValue = "12-20-2012 10:10:10 abcdexxxx";
try{
d=df.parse( currColValue );
}catch( ParseException e ){
System.out.println("Error parsing date: "+e.getMessage());
}
但无一异常(exception),String值被解析为Date。为什么?
最佳答案
根据 the Javadoc of the parse
method :
Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string.
(强调我的)。
与上面评论的含义相反,这与宽松的解析无关;相反,只是此方法不打算使用整个字符串。如果你想验证它消耗了整个字符串,我想你可以设置一个 ParsePosition
对象和 use the two-arg overload ,然后检查 ParsePosition
,看看它是否解析到字符串的末尾。
关于java - 为什么 java SimpleDateFormat 可以解析带有额外字符的格式化文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22033487/