Check simple date format? (YYYY-MM-dd'T'HH: mm: ss)

I'm going to test the simple date ( yyyy-MM-dd'T'HH:mm:ss

) format as follows. This implementation works for most of the basic validations, but for some reason I found that some of the validations did not work. For example, if you enter 2014-09-11T03:27:54kanmsdklnasd

, 2014-09-11T03:27:54234243

it is not confirmed. Could 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;
}

      

+3


source to share


2 answers


SimpleDateFormat.parse()

(which comes from DateFormat.parse()

) cannot be used for full blown validation as quoting from the javadoc :

The method may not use all the text for a given line.

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

to confirm.



The passed ParsePosition

parameter is "in-out", you can get information about this after calling the method parse()

:

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 good or bad for you!");
} else {
    System.out.println("Input is valid, parsed completely.");
}

      

+4


source


Using JodaTime is very easy.



import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

//from your method
String inputDateString = "2014-09-11T03:27:54kanmsdklnasd";
String pattern = "yyyy-MM-dd'T'HH:mm:ssZ";
boolean isValid = isValidDateFormat(inputDateString, pattern);

private boolean isValidDateFormat(String inputDateString, String format){
    try {
        DateTimeFormatter dtf = DateTimeFormat.forPattern(format);
        dtf.parseDateTime(inputDateString);
    } catch (Exception ex) {
        return false;
    }
    return true;
}

You will get..
 *Exception in thread "main" java.lang.IllegalArgumentException: 
 Invalid format: "2014-09-11T03:27:54kanmsdklnasd" is malformed at "kanmsdklnasd"*

      

+1


source







All Articles