简体   繁体   中英

How to make SimpleDateFormat.parse() fail hard?

I need this below code to start failing when the provided date string doesn't match the given format 100%.

SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
format.setLenient(false);
format.parse("09/10/20144");

For some reason even with setLenient(false) this call returns an actual 09/10/20144 date. I tried passing "new ParsePosition(0)" to the parse call but that doesn't help at all since the date still returns as 09/10/20144. I need any exceptions from the exact date format to fail hard. Is there any good way of doing that?

the string you give SDF only informs the formatter about the order and type of the input parts (the amount of information about the intervals for each field is limited, since he applies some calculations to make it "make" sense).

To achieve what you want, you can do an initial check using regular expression. In your case:

String input = "09/10/20144";
if (input == null || !input.matches("[01]\\d/[0123]\\d/[12]\\d{3}")) {
    throw new IllegalArgumentException("Invalid value or format");
} else {
    SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
    format.setLenient(false);
    format.parse(input);
}

The above regex checks that:

  • the month has 2 digits, first of which is either 0 or 1
  • the day has 2 digits with the first being one of {0,1,2,3}
  • the year has 4 digits with the first one 1 or 2.

More information on regular expressions in Java: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

Here's one way to do this, although it's slightly odd:

public static Date parseDate(String input) {
    final String format = "MM/dd/yyyy";
    if (input.length != format.length) { //Check the length, helps to avoid the cases mentioned earlier.
        throw new ParseException("Lengths do not match", 0);
    }
    SimpleDateFormat format = new SimpleDateFormat(format);
    format.setLenient(false);
    return format.parse(input);
}

(This is what I said in the comment earlier)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM