My requirement is to verify that the date string is in the correct format based on the set of valid formats.
Valid formats:
MM/dd/yy
MM/dd/yyyy
I created a simple testing method that uses Java 8 DateTimeFormatterBuilder to create flexible formatting that supports several optional formats. Here is the code:
public static void test() {
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendOptional(DateTimeFormatter.ofPattern("MM/dd/yy"))
.appendOptional(DateTimeFormatter.ofPattern("MM/dd/yyyy"))
.toFormatter();
String dateString = "10/30/2017";
try {
LocalDate.parse(dateString, formatter);
System.out.println(dateString + " has a valid date format");
} catch (Exception e) {
System.out.println(dateString + " has an invalid date format");
}
}
When I ran this, here is the output
10/30/2017 has an invalid date format
As you can see in the code, valid date formats are MM / dd / yy and MM / dd / yyyy. I expected the date 10/30/2017 to be valid, as it corresponds to MM / dd / yyyy. However, 10/30/2017 is reported as invalid.
What is going wrong? Why is this not working?
I also tried
.appendOptional(DateTimeFormatter.ofPattern("MM/dd/yy[yy]"))
instead
.appendOptional(DateTimeFormatter.ofPattern("MM/dd/yy"))
.appendOptional(DateTimeFormatter.ofPattern("MM/dd/yyyy"))
but still has the same problem.
This code works as expected if I use:
String dateString = "10/30/17";
instead
String dateString = "10/30/2017";
I have 2 questions