见代码:
/**
* 验证字符串是否为指定日期格式
*
* @param rawDateStr 待验证字符串
* @param pattern 日期字符串格式, 例如 "yyyy-MM-dd"
* @return 有效性结果, true 为正确, false 为错误
*/
public boolean dateStrIsValid(String rawDateStr, String pattern) {
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
Date date = null;
try {
// 转化为 Date类型测试判断
date = dateFormat.parse(rawDateStr);
return rawDateStr.equals(dateFormat.format(date));
} catch (ParseException e) {
log.error("Illegal date string! Exception occurred: {}",e.getMessage(),e);
return false;
}
}
参考: