I'd like to validate several date formats, as below examples :
YYYY
YYYY-MM
YYYY-MM-DD
Validation must ensure that date format is correct and the date exists.
I'm aware that Java 8 provides a new Date API, so I'm wondering if it's able to do such job.
Is there a better way using Java 8 date API ? Is it still a good practice to use Calendar class with lenient parameter ?
You can specify missing fields with parseDefaulting
to make all the formatters working:
public static boolean isValid(String input) {
DateTimeFormatter[] formatters = {
new DateTimeFormatterBuilder().appendPattern("yyyy")
.parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
.toFormatter(),
new DateTimeFormatterBuilder().appendPattern("yyyy-MM")
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
.toFormatter(),
new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd")
.parseStrict().toFormatter() };
for(DateTimeFormatter formatter : formatters) {
try {
LocalDate.parse(input, formatter);
return true;
} catch (DateTimeParseException e) {
}
}
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With