Complementing the response of Muril, despite validating the format, it turns out that the method passes some dates considered invalid (such as 30 February).
Using ResolverStyle on-mode Strict, you end up forcing Formatter to validate if the date, even having a valid date format, is actually 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;
}
}
Which 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 Soen. In this another question there is an explanation of why the use of u(new year representation) instead of y(year representation of an era) for formatting within the new API.
Simple, because it is Java.
– Maniero
What have you tried? The question is somewhat broad by the statement.
– user28595
I tried to do with array, but it has results that may not be valid dates and says it is.
– Gabriel Saldanha
How to migrate from Date and Calendar to the new Java 8 Date API?
– user28595
@diegfm I found this code, but it doesn’t compile. (I’m learning using Geany, no autocomplete and other help) Error On the catch line, on the Dateformat
class DataValida {
 public static void main(String[] args) {
 
 String s = "31/02/2009";
 DateFormat df = new SimpleDateFormat ("dd/MM/yyyy");
 df.setLenient (false); // aqui o pulo do gato
 try {
 df.parse(s);
 // data válida
 } catch (ParseException ex) {
 System.out.println("Data inválida");
 } 
 }
}– Gabriel Saldanha
I put the code between
and did not graduate– Gabriel Saldanha
If your intention is to learn how to manipulate dates in java, the post Inkei will give you plenty of content about, worth a read.
– user28595
I just saw, I’m gonna read
– Gabriel Saldanha
@Gabrielsaldanha saw my answer? She solves the problem?
– user28595