Open In App

How to Check Whether the Date is in the Proper Format Using Regex?

Last Updated : 21 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Regex is a very interesting way to search, test, and match for patterns in a String that the user provides. Regex stands for Regular Expressions. Using regex is in application forms, where the application checks whether the date entered by the user is in the valid format or not. An error message is displayed when the user types the wrong format of the date that the evaluator expects.

In this article, we will discuss how to Check whether the given date is in the proper format or not.

Example to check the proper format of the date:

Input 1: date = “02-08-2003”
Output 1: VALID Date Entered

Input 2: date= “02.8.23”
Output 2: INVALID Date Entered

Java Program to Check the Validity of the Date Format Using Regex

Below is the code implementation to validate the date:

Java




// Java Program to check the validity
// Of the Date format using Regex
import java.util.regex.Matcher;
import java.util.regex.Pattern;
  
public class CheckDate {
  
    public static boolean dateChecker(String date) 
    {
        String regexPattern = "^\\d{4}-\\d{2}-\\d{2}$";
        
      // \\d is used to match the numbers from 0-9
      Pattern standardPattern = Pattern.compile(regexPattern);
        
      // standartPattern represents the compiled regexPattern
      Matcher match = standardPattern.matcher(date);
        
      // match takes true or false based on the match
      return match.matches();
    }
  
    public static void main(String[] args) {
        
        String Birth_date_Entered = "2003-02-08";
  
        if (dateChecker(Birth_date_Entered)) 
        {
            System.out.println(Birth_date_Entered+ " is in valid format");
        } else {
            System.out.println(Birth_date_Entered + " is not in valid format");
        }
    }
}


Output

2003-02-08 is in valid format


Explanation of the above Program:

  • To check the validity of the date, we make use of the regex pattern matcher.
  • First, we have to provide a pattern that matches exactly with the Input String. Here \\d matcher the numbers from 0-9 and the number specified in the set brackets { } mentions the exact length of numbers to be present.
  • Then With the Pattern.compile() method we compile the regex pattern to a String.
  • The standardPattern.matcher(date) creates the matcher object for the date specified by the user with the use of the complied regex pattern.
  • .matcher() function returns a Boolean value based on whether the date matches the regex pattern or not.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads