1. SimpleDateFormatを使用します(ピット付き)
private static boolean isValidDate(String str) {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
try {
format.setLenient(false);
return format.parse(str)==null?false:true;
} catch (Exception e) {
return false;
}
}
上記の方法は検証できません。たとえば、日付文字列が202001011、202001010、長さが8桁を超えていますが、検証結果はtrueです。
2. java8で日付列検証を使用する
private static boolean isValid(String dateStr){
String format = "yyyyMMdd";
DateTimeFormatter ldt = DateTimeFormatter.ofPattern(format.replace("y", "u")).withResolverStyle(ResolverStyle.STRICT);
try {
return LocalDate.parse(dateStr, ldt)==null?false:true;
} catch (Exception e) {
return false;
}
}