Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating Java 8 dates

Tags:

java

java-8

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 ?

like image 857
Barium Scoorge Avatar asked Aug 25 '15 13:08

Barium Scoorge


1 Answers

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;
}
like image 74
Tagir Valeev Avatar answered Sep 18 '22 05:09

Tagir Valeev