当我将带有 "HH" 模式的日期字符串传递给 SimpleDateFormat 时,为什么我会得到一个日期?

Why do I get a date back when I pass a date string with a "HH" pattern to the SimpleDateFormat?

这是我的代码:

try {
  DateFormat dateFormat = new SimpleDateFormat(pattern);
  dateFormat.setLenient(false);
  Date date = dateFormat.parse(value);
  if (date != null) {
    return true;
  }
} catch (ParseException e) {}

1.) 当我将值作为“01/07/2015”传递并将模式作为 "HH:mm" 传递时,我正确地得到了一个异常。

2.) 但是,当我将值作为“01/07/2015”传递并将模式作为 "HH" 传递时,我得到一个 "Thu Jan 01 01:00:00 EST 1970" 日期对象。

除了场景 #2 之外,我还会抛出异常,因为给定的字符串与给定的模式完全不匹配。为什么即使设置了 setLenient(false) 也会得到那个奇怪的日期?

JavaDoc 很好地总结了为什么你没有得到异常:

Throws: ParseException - if the beginning of the specified string cannot be parsed.

01可以用HH解析,所以也不例外。

http://download.java.net/jdk6/archive/b104/docs/api/java/text/Format.html#parseObject(java.lang.String)

parseObject
public Object parseObject(String source)
                   throws ParseException
Parses text from the beginning of the given string to produce an object. The method may not use the entire text of the given string

我想#1 与分隔符不匹配。尽管模式是 :.

你还是把 / 放进去

并且 #2 在 HH 之后停止匹配,因为它从给定字符串的开头解析文本并且不使用给定字符串的整个文本。

我找到了解决这个问题的方法。 为了解决我的问题,我只是将我的整个代码包装在一个 if 语句中,我在其中检查模式的长度是否与值的长度相同,因为当我使用此代码进行验证时它们应该是:

if(StringUtils.length(pattern) == StringUtils.length(value)) {
  try {
    DateFormat dateFormat = new SimpleDateFormat(pattern);
    dateFormat.setLenient(false);
    Date date = dateFormat.parse(value);
    if (date != null) {
      return true;
    }
  } catch (ParseException e) {}
}
return false;