为什么java SimpleDateFormat可以解析带有额外字符的格式化文本? [英] Why java SimpleDateFormat can parse formatted text with extra characters?

查看:321
本文介绍了为什么java SimpleDateFormat可以解析带有额外字符的格式化文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 MM-dd-yyyy HH:mm:ss 格式解析用户输入的日期字符串,我发现 12-20- 2012 10:10:10 abcdexxxx 也可以被粘贴。怎么会发生这种情况?这是我的代码:

I am parsing date strings from user input with MM-dd-yyyy HH:mm:ss format, and I found 12-20-2012 10:10:10 abcdexxxx could be pasred as well. How can this happen? Here is my code:

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());
}

但没有例外,String值被解析为Date。为什么?

But there is no exception, the String value is parsed to be a Date. Why?

推荐答案

Per parse 方法的Javadoc:

Per 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 对象和使用双arg重载,然后检查 ParsePosition 以查看它是否解析为字符串的结尾。

Contrary to the implication of comments above, this has nothing to do with lenient parsing; rather, it's just that this method is not intended to consume the whole string. If you wish to validate that it consumed the whole string, I suppose you could set up a ParsePosition object and use the two-arg overload, and then examine the ParsePosition afterward to see if it parsed to the end of the string.

这篇关于为什么java SimpleDateFormat可以解析带有额外字符的格式化文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆