You can parse each date and its numbers in a try/catch
block, and increment a counter as follows:
public static void main(String[] args) {
String[] dates = new String[]{"car","bench","01/04/2019", "01/13/2019", "29/02/200s"};
System.out.println(validate(dates));
}
private static int validate(String[] dates){
int count = 0;
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
format.setLenient(false);
for(String date : dates) {
try {
format.parse(date);
String[] dateParts = date.split("/");
for(String str : dateParts)
Integer.parseInt(str);
if(dateParts.length!=3 || dateParts[0].length()!=2 || dateParts[1].length()!=2 || dateParts[2].length()!=4)
throw new Exception();
count++;
} catch (Exception e) {
System.out.println("Date " + date + " is not valid");
}
}
return count;
}
Output:
Date car is not valid
Date bench is not valid
Date 01/13/2019 is not valid
Date 29/02/200s is not valid
1
EDIT :
According to Ole's comment and this post, it's better to use more accurate libraries:
public static void main(String[] args) {
String[] dates = new String[]{"car","bench","01/04/2019", "01/13/2019", "29/02/200s"};
System.out.println(validate(dates));
}
private static int validate(String[] dates){
int count = 0;
for(String date : dates) {
try {
String[] dateParts = date.split("/");
if(dateParts.length==3 && isDateValid(Integer.parseInt(dateParts[2]), Integer.parseInt(dateParts[1]), Integer.parseInt(dateParts[0])))
count++;
else
throw new Exception();
} catch (Exception e) {
System.out.println("Date " + date + " is not valid");
}
}
return count;
}
private static boolean isDateValid(int year, int month, int day) {
boolean dateIsValid = true;
try {
LocalDate.of(year, month, day);
} catch (DateTimeException e) {
dateIsValid = false;
}
return dateIsValid;
}