Java Date Format Validation Using Regular Expressions

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




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

Join Telegram channel at https://t.me/techlistic
Feel free to ask queries or share your thoughts in comments or email me.

Comments

Post a Comment

Popular Posts

Top 10 Demo Websites to Practice Selenium Webdriver Online

Selenium WebDriver - Take Screenshot and Partial Screenshot Commands

Top 25 Must to know Selenium Webdriver Commands List

Selenium Essentials - How to become expert in Automation Testing?

Selenium WebDriver - Browser and Navigation Commands