简体   繁体   中英

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;
}

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.");
}

Using JodaTime it 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"*

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