How to check if the date is valid or invalid?

0

I'm learning Java on my own and I came across an exercise that I do not know where to start searching. I found something about datetime, try, catch. But I could not quite understand why the examples were much more complex than my problem.

Could someone give me a direction on the datetime and some method that I can know that will help me with this exercise?

My exercise statement is:

   //Faça um Programa que peça uma data no formato dd/mm/aaaa 
   //e determine se a mesma é uma data válida.
    
asked by anonymous 01.03.2017 / 23:41

2 answers

8

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.

    
02.03.2017 / 02:18
0

Using the Java 8 API, you can test with LocalDate and parse, as follows:

public class DateValidator {

   public boolean isValid(String date) {
      try {
         DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
         LocalDate d = LocalDate.parse(date, formatter);    
         return true;
      } catch (DateTimeParseException e) {
        return false;
      }   
   }
}

Run the created class via Ideone .

    
02.03.2017 / 00:42