Home > Mobile >  Counting the right data formats
Counting the right data formats

Time:10-11

im stuck at a problem where i need to make a class which counts all the right data formats given to a string.

Requirement: Write a ValidatorDate class that contains the following public countValidData enumeration.

The method will receive as a parameter a string of Strings (String[]) and will return an int representing the number of Strings in the string that respect the format dd/mm/yyyy.

Signature:

public static int countValidData(String[] words)

Example:

//Your class here
    public class prog {
      public static void main(String[] args) {
        System.out.println(ValidatorDate.countValidData(new String[]{"Today", "is", "01/04/2019", "01/13/2019",
          "29/02/200s"}));
        // 2
      }
    }

and this is what i've done so far

import java.util.Arrays;
import java.util.regex.Pattern;

class ValidatorDate {

    static int countValidData(String[] arrayDate) {

        Pattern regexPattern = Pattern.compile("^\\d{2}/\\d{2}/\\d{4}$");

        int counter = 0;

        for (String currentWord : arrayDate) {


            if (regexPattern.matcher(currentWord).matches()) {

                counter  ;

            }

        }

        return counter;
    }
}

This code needs a fix, if i introduce for example, the following date: "99/99/9999" it sees it as a valid date, i dont have this "only 12 months" and "30 or 31 days, or 28 in february" implementation, can someone help me with it? Thanks in advance!

CodePudding user response:

Use DateTimeFormatter

static int countValidData(String[] arrayDate) {
    int counter = 0;

    for (String currentWord : arrayDate) {
       try {
           DateTimeFormatter.ofPattern("dd/MM/yyy").parse(currentWord);
           counter  ;
       }catch (DateTimeParseException e){
            //log to  see what is wrong
       }

    }

    return counter;
}

CodePudding user response:

First import as needed

import java.time.format.DateTimeFormatter;
import java.time.LocalDate;

Now, you can utilize DateTimeFormatter and LocalDate

static int countValidData(String[] arrayDate) {
    
        //Initialize DateTimeFormatter
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");

        int counter = 0;

        for (String currentWord : arrayDate) {

            try {
                
                //Try to convert String to LocalDate
                LocalDate localDate = LocalDate.parse(date, formatter);
                
                //Increment counter by 1
                counter  = 1;
                
            } catch (Exception e){
                //If an exception was thrown, the date is invalid
            }

        }

        return counter;
}
  • Related