How to Validate Date Format using Regular Expressions in Java

In this tutorial, you will learn to match date format using Regular Expressions in Java.

Regular Expression is a sequence of symbols and characters which define a search pattern, used for pattern matching with strings. Regular Expression is also known as regex. It is mainly used for finding or validating strings and also for replace string operations. It's a very handy and powerful tool which comes along in every programming language.

Java Program to check Date Format

package com.techlistic.javaprograms;

class ValidateDateFormat{

 public static void main(String[] args) {
  
  // Pass Date Format 
  validateDateFormat("15/12/2019");
  
 }
 
 // Check the Date format to be MM/dd/yyyy
 private static boolean validateDateFormat(String date){

  // Store date format in String buffer
  StringBuffer sBuffer = new StringBuffer(date);
  String mon;
  String dd;
  String year;

  // Store the Date in String Buffer and Break down the date
  // 0,2 - Month
  // 3,5 - Date
  // 6,10 - Year
  mon = sBuffer.substring(0,2);
  dd = sBuffer.substring(3,5);
  year = sBuffer.substring(6,10);

  System.out.println("DD: "+ dd + " Mon: "+ mon + " Year: "+ year);

  // Validating Date Format for Turn In Date and Live Date to be MM/dd/yyyy using regular expression
  if(mon.matches("0[1-9]|1[0-2]") && dd.matches("0[1-9]|[12][0-9]|3[01]") && year.matches("(19|20)\\d\\d"))
  {
   System.out.println("Date Format matched.");
   return true;
  }
  else
  {
   System.out.println("Date Format didn't matched.");
   return false;
  }
 }

}







Program Explanation:
  1. Store the date format value in a String Buffer.
  2. Split the date format using substring() method into 3 different parts:
    • Month
    • Date
    • Year
  3. Match 3 parts with regular expressions,
    • 0[1-9]|1[0-2] - This regular expression validates the value of month. It means, 
      • 0[1-9] - If  first digit is 0 then second digit can be from 0-9. Or,
      • 1[0-2] - If first digit is 1 then second digit can be from 0-2.
    • 0[1-9]|[12][0-9]|3[01] - This regular expression validates the value of day.
      • 0[1-9] - If  first digit is 0 then second digit can be from 0-9. Or,
      • [12][0-9] - If first digit is 1 or 2 then second digit can be from 0-9. Or,
      • 3[01] - If the first digit is 3 then the second digit can be 0 or 1.
    • 19|20)\\d\\d - This expression validates year,
      • It checks that year can start with 19 or 20 and the last two values can be any digit.
Refer Java Tutorial Series


Follow Us

Quora Space | Facebook Page | Telegram Channel
Feel free to ask queries or share your thoughts in comments or email us.

Comments

Popular posts from this blog

10 Best Demo Websites for Automation Testing Practice

Automate 'User Registration' of E-commerce Website using Selenium

Automate Browser Actions on Godaddy.com using Selenium

Selenium WebDriver Browser and Navigation Commands