Auro
Auro

Reputation: 1628

How do I find out the actual cause of parse exception in SimpleDateFormat?

I have a date in the form of String that I'm validating using SimpleDateFormat.

I have the following piece of code for that:

public boolean validateDate(String date) {

    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
    format.setLenient(false);
    try {
        Date dt = format.parse(date);
        logger.info("DT:\t" + dt.toString());
        String actDate = format.format(dt);
        logger.info("actDate:\t" + actDate);
        return actDate.equals(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return false;
}

Now if I send a value that doesn't have the same format my formatter is expecting (e.g. 29-03--2008) or a value that has incorrect leap year (e.g. 29-02-2007), I get a java.text.ParseException: Unparseable date:

I want to be able to know what exactly caused the problem so that I can send an appropriate message back to the one calling the method. However, when the exception occurs, I have no way to know what exactly caused it (whether it was an invalid format or an incorrect value or something else).

I can use RegEx to check if the format is correct, but then SimpleDateFormat is already taking care of that check internally. So I don't want to do the same thing again.

Is there any way for me to know what caused the exception?

Upvotes: 1

Views: 1418

Answers (2)

Darshan Mehta
Darshan Mehta

Reputation: 30819

Here's the javadoc for parse method, this is what it says:

Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string.

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

It throws ParseException as soon as it finds out that the String can't be parsed. As it never parses the full String (unless it ParseException gets thrown while parsing the last character), you won't know the exact reason why it failed (i.e whether it was invalid format or invalid date).

Closest you can get to it is by parsing the date by both with and without setting lenient to false. If former throws an Exception but latter works fine, you can tell for sure that it's invalid date and not format.

Upvotes: 0

Jason
Jason

Reputation: 11832

I suspect there are nearly an infinite number of ways that a date can be misformatted. Collectively, our code will probably experience all of them, given enough time.

You may find the simplest (best?) method is simply to include the malformed date in the error message so that the user can see what they did wrong.

Edit: Take care to escape the entered value such that you don't introduce an XSS or similar vulnerability into your system.

Upvotes: 1

Related Questions