If the user should just enter a date (such as 2019-03-31
), there is no reason why your program should be concerned with time of day too. Furthermore, your format is ISO 8601, the format that LocalDate
and the other the classes of java.time parse (and also print) as their default. So you don’t need an explicit formatter.
I understand that you want a range check, which is certainly advisable. In addition, if a user enters a completely different format, parsing will throw a DateTimeParseException
which you should catch and act accordingly. For example:
LocalDate minAcceptedDate = LocalDate.of(0, Month.JANUARY, 1);
LocalDate maxAcceptedDate = LocalDate.of(4000, Month.DECEMBER, 31);
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter Date : ");
while (true) {
String time = keyboard.next();
try {
LocalDate dateTime = LocalDate.parse(time);
if (dateTime.isBefore(minAcceptedDate) || dateTime.isAfter(maxAcceptedDate)) {
System.out.println("Please enter a date in the range " + minAcceptedDate + " through " + maxAcceptedDate);
} else { // OK
break;
}
} catch (DateTimeParseException dtpe) {
System.out.println("Please enter a date in format yyyy-mm-dd");
}
}
Example session:
Please enter Date :
Yesterday
Please enter a date in format yyyy-mm-dd
-001-12-30
Please enter a date in format yyyy-mm-dd
5000-12-12
Please enter a date in the range 0000-01-01 through 4000-12-31
2016-09-22