I have the below java code, it works if user input date of the specified format e.g 2011-11-11 but the program crashes when user enters plain text e.g 'hello', 'yes'. The code compares user input date with current date and perform action. How do I check to make sure that user enter date and not plain text before the program can continue. Here is the code:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
System.out.println("Enter valid date e.g yyyy-mm-dd: ");
String date = sn.next();
LocalDate startDate = LocalDate.parse(date, formatter); //I don't want the program to accept 'startDate' as test, it should be date of specified förmat before jumping to try and catch.
LocalDateTime lt = LocalDateTime.now();
LocalDate currentDate = lt.toLocalDate(); // for type match, I removed time stamp from the localdatetime
try {
for (obj result : list) {
if (startDate.isBefore(currentDate)) {
System.out.println(result);
} else {
System.out.println("");
}
}
} catch (DateTimeException e) {
System.out.println ( "ERROR: " + e );
}