为什么非宽松的SimpleDateFormat用字母解析日期?

Ble*_*lem 12 java simpledateformat

当我运行以下代码时,我会期待一个堆栈跟踪,但它似乎忽略了我的的错误部分,为什么会发生这种情况?

package test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test {
  public static void main(final String[] args) {
    final String format = "dd-MM-yyyy";
    final String value = "07-02-201f";
    Date date = null;
    final SimpleDateFormat df = new SimpleDateFormat(format);
    try {
      df.setLenient(false);
      date = df.parse(value.toString());
    } catch (final ParseException e) {
      e.printStackTrace();
    }
    System.out.println(df.format(date));
  }

}
Run Code Online (Sandbox Code Playgroud)

输出是:

07-02-0201

Jay*_*han 11

DateFormat.parse(由SimpleDateFormat继承)的文档说:

The method may not use the entire text of the given string.
Run Code Online (Sandbox Code Playgroud)
final String value = "07-02-201f";
Run Code Online (Sandbox Code Playgroud)

在你的情况下(201f)它能够解析有效字符串直到201,这就是为什么它没有给你任何错误.

同一方法的"引发"部分定义如下:

ParseException - if the beginning of the specified string cannot be parsed
Run Code Online (Sandbox Code Playgroud)

因此,如果您尝试将字符串更改为

final String value = "07-02-f201";
Run Code Online (Sandbox Code Playgroud)

您将获得解析异常,因为无法解析指定字符串的开头.


Joo*_*gen 5

您可以查看整个字符串是否被解析如下。

  ParsePosition position = new ParsePosition(0);
  date = df.parse(value, position);
  if (position.getIndex() != value.length()) {
      throw new ParseException("Remainder not parsed: "
              + value.substring(position.getIndex()));
  }
Run Code Online (Sandbox Code Playgroud)

此外,当一个异常被抛出parseposition也将产生getErrorIndex()