How to check if the given date is valid or not in Java

Hey Everyone! In this article, we will learn how we can check if a given date is valid or not in Java.


For a given date to be valid we have to check two conditions which are as follows:-
1. It should be in the specified format i.e in dd/mm/yyyy format.
2. It should exist in the Calendar i.e 30/02/2013 doesn’t exist.

Let’s have a look at the code:-

Java program to check if a given date is valid or not

The below program will check the date is valid or invalid. The output is also given.

package datevalidation;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Scanner;

public class DateValidation {

    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        
        System.out.println("Enter a date in dd/mm/yyyy format");
        
        String date = sc.next();
        
        if(dateValidation(date)==true)
            System.out.println("Date is valid");
        else
            System.out.println("Date is invalid");
        
        
            
    }
    
    private static boolean dateValidation(String date)
    {
      boolean status = false;

    if (checkDate(date)) {
      DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
      dateFormat.setLenient(false);
      try {
        dateFormat.parse(date);
        status = true;
      } catch (Exception e) {
        status = false;
      }
    }
    return status;
    }
    
    static boolean checkDate(String date) {
    String pattern = "(0?[1-9]|[12][0-9]|3[01])\\/(0?[1-9]|1[0-2])\\/([0-9]{4})";
    boolean flag = false;
    if (date.matches(pattern)) {
      flag = true;
    }
    return flag;

  }
    
}
Input

Enter a date in dd/mm/yyyy format
30/12/2019

Enter a date in dd/mm/yyyy format
30/02/1990

Enter a date in dd/mm/yyyy format
12/12/12
Output

Date is valid
Date is invalid
Date is invalid

In the above code snippet, we have created an object of DateFormat class and passed a format for the date in the constructor.
By default setLenient() method is true i.e it won’t check if the date exists in reality or not.
Hence we have made it false so that it checks whether the given date exists or not.
In the check date method, we have written a regular expression which checks the following:-

1. dd -> 1-31
2. mm -> 1-12
3. yyyy -> 4 digit number

I hope you have understood the above program.
If you have any doubts or suggestions please leave a comment down below.

Also learn:

Leave a Reply

Your email address will not be published. Required fields are marked *