Java 一旦匹配模式,Simpledateformat 似乎会忽略字符串

Java Simpledateformat seems to ignore string once matches the pattern

SimpleDateFormat 似乎在找到匹配模式后忽略匹配字符串中的字符串。

例如:模式 "yyyyMMddHHmm"201601251531oi 匹配,我认为它不应该匹配。然而,这个 20160125153133 失败了,这是完全正确的。 我试过 setLenienttrue 但没有效果。我知道我们可以添加另一个数字位数检查(正则表达式),但是有没有办法严格地使这个模式只使用 SimpleDateFormat 单独工作?

public static boolean isValidDateTimeFormat(String anyString,
                    String dateTimePattern) {
                 // here the pattern is 'yyyyMMddHHmm'
                SimpleDateFormat datePattern = new SimpleDateFormat(dateTimePattern); 
                datePattern.setLenient(false); // no difference
                try {
                    datePattern.parse(anyString);
                    return true;
                }
                catch (Exception pe){
                    return false;
                }
      }

不,正如@ControlAltDel 在评论中所述,SimpleDateFormat 不会以这种方式工作。您需要:

  1. 添加额外的验证
  2. 判断多余字符为"ok",使用SimpleDateFormat解析出来的数据