[英]Validate a simple time date format ? (yyyy-MM-dd'T'HH:mm:ss)
我將驗證一個簡單的時間日期格式( yyyy-MM-dd'T'HH:mm:ss
),如下所示。 這個實現適用於大多數主要驗證但不知何故我發現一些驗證似乎不起作用。 例如,如果您輸入2014-09-11T03:27:54kanmsdklnasd
, 2014-09-11T03:27:54234243
它不會驗證。 你能指出我的代碼錯誤嗎?
碼
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()
(來自DateFormat.parse()
)不能用於全字符串驗證,因為它的javadoc引用:
該方法可能不使用給定字符串的整個文本 。
相反,您可以使用DateFormat.parse(String source, ParsePosition pos)
進行驗證。
您傳遞的ParsePosition
是一個“in-out”參數,您可以在調用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's good or bad for you!");
} else {
System.out.println("Input is valid, parsed completely.");
}
使用JodaTime非常容易 。
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"*
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.