Date Validation – Use SimpleDateFormat

Get a date as String from user. Check if that date is a valid date using SimpleDateFormat.

Date entered by the user is in the format dd/MM/yyyy

If the given date is valid then display “ is a valid date”. Else display “ is not a valid date”.

Sample Input 1

31/08/2020

Sample Output 1

31/08/2020 is a valid date

Sample Input 2

31/11/2020

Sample Output 2

31/11/2020 is not a valid date

This is what I have tried till now but there is no output: enter image description here

Answer

Change your code like that:

        SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        df.setLenient(false);
        String source = "30/11/2020";
        try {
            df.parse(source);
            System.out.println(source + " is valid");
        } catch (ParseException e) {
            System.out.println(source + " is not valid");
        }