A common way to validate user input is by trying to parse it and seeing if that succeeds. That also works here. Java has nice built-in facilities for parsing dates in various fixed formats, so I suggest you use these:
private static final DateTimeFormatter PARSE_FORMATTER
= DateTimeFormatter.ofPattern("MM/dd/uuuu");
public static void main(String [] dateValidation)
{
try (Scanner kb = new Scanner(System.in)) {
System.out.println("Please enter a date (mm/dd/yyyy)");
String uDate = kb.nextLine();
try {
LocalDate.parse(uDate, PARSE_FORMATTER);
System.out.println(uDate + " is a valid Date");
} catch (DateTimeParseException dtpe) {
System.out.println(uDate + " is a not valid Date");
}
}
}
This accepts 06/17/2017
but rejects 6/17/2017
because the month hasn’t got two digits. Beware that the format pattern string MM/dd/uuuu
is case sensitive (it has to be uppercase M
and lowercase d
and u
).
If you want to allow one-digit months and days, change the formatter to
private static final DateTimeFormatter PARSE_FORMATTER
= DateTimeFormatter.ofPattern("M/d/uuuu");
Now all of 7/2/2017
, 07/02/2017
and 12/25/2017
are accepted.
Not related to your question, I have used try-with-resources for making sure the Scanner
is closed after use. This also closes standard input.
Question: does this work in Java 8 only? No, the modern date and time API that I am using has been backported to Java 6 and 7 in ThreeTen Backport and especially for Android in ThreeTenABP (and then of course it works in Java 9, due this summer, and later versions…).