14

When I run the following code I would expect a stacktrace, but instead it looks like it ignores the faulty part of my value, why does this happen?

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

}

The output is:

07-02-0201

4

3 回答 3

12

The documentation of DateFormat.parse (which is inherited by SimpleDateFormat) says:

The method may not use the entire text of the given string.
final String value = "07-02-201f";

In your case (201f) it was able to parse the valid string till 201, that's why its not giving you any errors.

The "Throws" section of the same method has defined as below:

ParseException - if the beginning of the specified string cannot be parsed

So if you try changing your string to

final String value = "07-02-f201";

you will get the parse exception, since the beginning of the specified string cannot be parsed.

于 2013-02-13T10:22:08.637 回答
5

You can look whether the entire string was parsed as follows.

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

Furthermore when an exception was thrown by parse the position will also yield getErrorIndex().

于 2013-02-13T10:36:48.553 回答
1

Confirmed... I also found that "07-02-201", "07-02-2012 is the date" compiles. However, "bar07-02-2011" does not.

From the code in SimpleDateFormat, it seems like the parsing terminates the moment an illegal character is found that breaks the matching. However, if the String that has already been parsed up to that point is valid, it is accepted.

于 2013-02-13T10:28:02.450 回答