Complementing the response of the Murilo , although validating the format, it ends up that the method lets pass some dates considered invalid (such as February 30).
Using ResolverStyle
in Strict
, you end up forcing the formatter to validate if the date, even having a valid date format, is really a valid date:
public static void main (String[] args) {
System.out.println("29/02/2016 eh uma data valida? " + isDateValid("29/02/2016"));
System.out.println("29/02/2017 eh uma data valida? " + isDateValid("29/02/2017"));
System.out.println("31/06/2017 eh uma data valida? " + isDateValid("30/01/2017"));
System.out.println("31/04/2017 eh uma data valida? " + isDateValid("31/04/2017"));
}
public static boolean isDateValid(String strDate) {
String dateFormat = "dd/MM/uuuu";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter
.ofPattern(dateFormat)
.withResolverStyle(ResolverStyle.STRICT);
try {
LocalDate date = LocalDate.parse(strDate, dateTimeFormatter);
return true;
} catch (DateTimeParseException e) {
return false;
}
}
That will result in:
29/02/2016 eh uma data valida? true //2016 é bissexto, data válida
29/02/2017 eh uma data valida? false //inválida
31/06/2017 eh uma data valida? true //data válida
31/04/2017 eh uma data valida? false //abril só tem 30 dias, data inválida
See a test on Ideone
This response was based on this one from SOEn . In this other question there is an explanation of why using u
(new year representation) instead of y
(year-old representation of an era) for formatting within the new API.