Search code examples
javasimpledateformat

Validate a simple time date format ? (yyyy-MM-dd'T'HH:mm:ss)


I'm going to validate a simple time date format (yyyy-MM-dd'T'HH:mm:ss) as follows. This implementation works for most major validations but somehow I found some validations doesn't seems to be working. such as if you enter 2014-09-11T03:27:54kanmsdklnasd , 2014-09-11T03:27:54234243 it doesn't validate. Can you please point out my code error?

code

String timestamp = "2014-09-11T03:27:54";
SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try{
    format.parse(timestamp);
    LOG.info("Timestamp is a valid format");
}
catch(ParseException e)
{
    return ssoResponse;
}

Solution

  • SimpleDateFormat.parse() (which comes from DateFormat.parse()) cannot be used for full-string validation because quoting from its javadoc:

    The method may not use the entire text of the given string.

    Instead you can use the DateFormat.parse(String source, ParsePosition pos) to validate.

    The ParsePosition you pass is an "in-out" parameter, you can get info out of it after you call the parse() method:

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    // If you set lenient to false, ranges will be checked, e.g.
    // seconds must be in the range of 0..59 inclusive.
    format.setLenient(false);
    
    String timestamp = "2014-09-11T03:27:54";
    ParsePosition pos = new ParsePosition(0);
    
    format.parse(timestamp, pos); // No declared exception, no need try-catch
    
    if (pos.getErrorIndex() >= 0) {
        System.out.println("Input timestamp is invalid!");
    } else if (pos.getIndex() != timestamp.length()) {
        System.out.println("Date parsed but not all input characters used!"
             + " Decide if it's good or bad for you!");
    } else {
        System.out.println("Input is valid, parsed completely.");
    }