How to Check whether the date is valid or invalid?

Asked

Viewed 9,290 times

0

I’m learning Java on my own and I came across an exercise that I don’t know where to start researching. I found something about datetime, Try, catch. But I couldn’t quite understand why the examples were much more complex than my problem.

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

My statement from the exercise is:

   //Faça um Programa que peça uma data no formato dd/mm/aaaa 
   //e determine se a mesma é uma data válida.
  • Simple, because it is Java.

  • What have you tried? The question is somewhat broad by the statement.

  • I tried to do with array, but it has results that may not be valid dates and says it is.

  • @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");
 } 
 }
}

  • I put the code between and did not graduate

  • 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.

  • I just saw, I’m gonna read

  • @Gabrielsaldanha saw my answer? She solves the problem?

Show 4 more comments

2 answers

8

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.

  • 1

    very cool @diegofm, thanks for sharing.

0

Using the Java 8 API, you can test with LocalDate and the parse method 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 class created via Ideone.

  • 3

    Your code is validating several invalid dates, see: https://ideone.com/y44z0s

Browser other questions tagged

You are not signed in. Login or sign up in order to post.