Nikos Maravitsas

About Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.

Validate Date with Java Regular Expression example

In this tutorial we are going to see how to validate date format with Java Regular Expressions.The basic policy about  date of the form “dd/mm/yyyy” is that:

  • It should start with two digits from 01 – 31 or from 1 – 31.
  • It must be followed by ‘/’.
  • It should be followed by two digits from 01- 12 or from 1 – 12.
  • It must then be followed by “/”
  • It must the be followed by a number between 1900 and 2099.

 
 
 
So this is the regular expression we are going to use for 12 hours format validation:

(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)

You can take a look at the Pattern class documentation to learn how to construct your own regular expressions according to your policy.

The hard thing in date formats is that it is a bit hard to embed other constraints in tha regulare expression, like even months have 31 days and odd have 30, February has 28 or 29 years on the year leap.

1. Validator clas.

This is the class that we are going to use for date format validation.

DateFormatValidator.java:

package com.javacodegeeks.java.core;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DateFormatValidator{

  private Pattern pattern;
  private Matcher matcher;

  private static final String DATE_VALIDATION_PATTERN = "(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)";

  public DateFormatValidator(){
	  pattern = Pattern.compile(DATE_VALIDATION_PATTERN);
  }

   public boolean validate(final String date){

     matcher = pattern.matcher(date);

     if(matcher.matches()){

	 matcher.reset();

	 if(matcher.find()){

         String dd = matcher.group(1);
	     String mm = matcher.group(2);
	     int yy = Integer.parseInt(matcher.group(3));

	     if (dd.equals("31") &&  (mm.equals("4") || mm .equals("6") || mm.equals("9") ||
                  mm.equals("11") || mm.equals("04") || mm .equals("06") ||
                  mm.equals("09"))) {
			return false;
	     } else if (mm.equals("2") || mm.equals("02")) {

		  if(yy % 4==0){
			  if(dd.equals("30") || dd.equals("31")){
				  return false;
			  }else{
				  return true;
			  }
		  }else{
		         if(dd.equals("29")||dd.equals("30")||dd.equals("31")){
				  return false;
		         }else{
				  return true;
			  }
		  }
	      }else{				 
		return true;				 
	      }
	   }else{
    	      return false;
	   }		  
     }else{
	  return false;
     }			    
   }
}

2. Unit Testing our DateFormatValidator class

For unit testing we are going to use JUnit. Unit testing is very important in these situations because they provide good feedback about the correctness of our regular expressions. You can test your program and reassure that your regular expression meets the rules on your policy about the form of date format.

This is a basic test class:

DateFormatValidatorTest.java:

package com.javacodegeeks.java.core;

import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.Collection;

import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class DateFormatValidatorTest {

	private String arg;
	private static DateFormatValidator dateFormatValidator;
	private Boolean expectedValidation;

	public DateFormatValidatorTest(String str, Boolean expectedValidation) {
		this.arg = str;
		this.expectedValidation = expectedValidation;
	}

	@BeforeClass
	public static void initialize() {
		dateFormatValidator = new DateFormatValidator();
	}

	@Parameters
	public static Collection<Object[]> data() {
		Object[][] data = new Object[][] {
				{ "11/11/11", false },    // we want the full year description
				{ "2013/23/12" , false }, // wrong format
				{ "1-10-2013", false },   // wrong format
				{ "32/12/2020", false },  // out of range
				{ "31/04/2013", false },  // April has 30 days

				

				{ "5/1/2013", true },                         
				{ "04/04/2009", true },
				{ "28/2/2012", true } };

		return Arrays.asList(data);
	}

	@Test
	public void test() {
		Boolean res = dateFormatValidator.validate(this.arg);
		String validv = (res) ? "valid" : "invalid";
		System.out.println("Date Format "+arg+ " is " + validv);
		assertEquals("Result", this.expectedValidation, res);
	}
}

Output:

Date Format 11/11/11 is invalid
Date Format 2013/23/12 is invalid
Date Format 1-10-2013 is invalid
Date Format 32/12/2020 is invalid
Date Format 31/04/2013 is invalid
Date Format 5/1/2013 is valid
Date Format 04/04/2009 is valid
Date Format 28/2/2012 is valid

 
This was an exampl on how to validate date format with Java Regular Expression.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close