1

I'm using this SimpleDateFormat yyyy/MM/dd to pass a date value from String to Date. But there is this issue: when I input a non-date value, like 2020/12/2x, it will return to 2020/12/02. And when I try 2020/12/x2, the function will return an error. Anyone know why this is happening? Thank you so much. Here is my code.

Declare SimpleDateFormat

    SimpleDateFormat df2 = new SimpleDateFormat("yyyy/MM/dd");
    df2.setLenient(false);

Function I used to check if the string I input is a valid date or not

    private static Boolean validDate(DateFormat df, String s) {
    Boolean valid=false;
    try {
        Date d= df.parse(s);
        valid=true;
    } catch (Exception e) {
         valid=false;
    }
    return valid;
}

I used input:

2020/12/2x

2 Answers2

2

The SimpleDateFormat class contains many corner cases with unexpected behavior (as pointed out in a comment the DateFormat.parse(String) Javadoc says the method may not use the entire text of the given string), and has long been deprecated in favor of classes in the java.time package. For example,

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate d = LocalDate.parse("2020/12/2x", formatter);
System.out.println(formatter.format(d));

Is consistent, and throws java.time.format.DateTimeParseException: Text '2020/12/2x' could not be parsed at index 8

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • 2
    Answer will be better if you also explain what's actually going wrong with the old API, which is actually well-documented in the javadoc of [`DateFormat::parse(String)`](https://docs.oracle.com/javase/8/docs/api/java/text/DateFormat.html#parse-java.lang.String-): *"The method may not use the entire text of the given string"*. Yeah, it's one of the many flaws of the old API. – Andreas Dec 24 '20 at 05:11
0

I think the parse(string) method just travel from index zero to the farthest possible index where it can parse the source string to a correct date and does not care about remaining characters. It makes result of

df2.parse("2020/12/2x")

equivalent to result of

df2.parse("2020/12/2xxxxxxx_anything_goes_here")

In case of df2.parse("2020/12/x2"). When the method travels to x character, it realize that there is no date satisfying "2020/12/x", so it immediately throws an exception.

TaQuangTu
  • 2,155
  • 2
  • 16
  • 30