SimpleDateFormat Unexpected Success with Phone Number

Accidentally passing in a phone number string into the format method of SimpleDateFormat sometimes results in a valid date being parsed.

As an example, passing the number "518-123-4567" (literal, with hyphens) somehow results in the date "11/23/0517 05:27 AM"

We are using this in an area where a String could represent a number of different things, and we were under the assumption that a string with digits and hyphens in the way that a phone number is typically written would fail when parsed as a date. Our code simply checks to ParseException, and accepts anything that does not throw such an exception as valid. Why doesn't this sort of string fail parsing? Is there a better way to check to see if a string could potentially be or not be a date?

private static Date getPromisedDate(String promisedText) {
    SimpleDateFormat promsiedDateTimeFormat = new SimpleDateFormat("yyyyMMddHHmm"); 
    if(null != promisedText) {
        try {
            return promsiedDateTimeFormat.parse(promisedText);          
        }
        catch (ParseException e) { }
    }            
    return null;
}
Jon Skeet
people
quotationmark

Your SimpleDateFormat is in "lenient" mode - which is very lenient indeed. If you use

promsiedDateTimeFormat.setLenient(false);

it will throw an exception as you'd expect when you try to parse the bogus data.

Personally I think it should be strict by default, but...

people

See more on this question at Stackoverflow