Quantcast
Channel: Kushal's Java Blog | Software Engineering Blog » Java Regular Expressions - Kushal's Java Blog | Software Engineering Blog
Viewing all articles
Browse latest Browse all 12

Date Format Validation (mmddyy and ddmmyy) in Java Using Regular Expressions

$
0
0

The following java program has the capability of doing the date format validation in software using regular expressions and is able to validate both mmddyy and ddmmyy date formats (of course the date, month and year can be separated using punctuations or delimiters).

package com.kushal.tools;
/**
 * @author Kushal Paudyal
 * Last Modified on 2010/12/21
 * 
 * This class demonstrates the use of regular expressions to validate Dates
 * It basically validates two formats of dates:MMDDYYYY & DDMMYYYY
 * Both of these validations accept -, / and . as delimiters.
 * 
 * www.sanjaal.com/java
 */

import java.util.regex.Pattern;

public class DateValidatorRegex {
	
	static String regexMMDDYYYY="^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\\d\\d$";
	static String regexDDMMYYYY="^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\\d\\d$";
	
	public static void main (String [] args ) {
		/**Testing for MMDDYYYY**/
		System.out.println("TEST FOR MMDDYYYY");
		System.out.println(isAValidMMDDYYYYDate("07-20-1982"));//true
		System.out.println(isAValidMMDDYYYYDate("07/20/1982"));//true
		System.out.println(isAValidMMDDYYYYDate("07.20.1982"));//true
		System.out.println(isAValidMMDDYYYYDate("07201982"));//false
		System.out.println(isAValidMMDDYYYYDate("20.07.1982"));//false
		
		/**Testing for MMDDYYYY**/
		System.out.println("\nTEST FOR DDMMYYYY");
		System.out.println(isAValidDDMMYYYYDate("20-07-1982"));//true
		System.out.println(isAValidDDMMYYYYDate("20/07/1982"));//true
		System.out.println(isAValidDDMMYYYYDate("20.07.1982"));//true
		System.out.println(isAValidDDMMYYYYDate("20071982"));//false
		System.out.println(isAValidDDMMYYYYDate("07.20.1982"));//false
		
	}
	/**
	 * @param date
	 * MMDDYYYY DATE VALIDATION
	 * It can validate the following three kinds of dates:
	 * 07-20-1982
	 * 07/20/1982
	 * 07.20.2982
	 */
	public static boolean isAValidMMDDYYYYDate(String date) {
		return Pattern.matches(regexMMDDYYYY, date);
	}
	
	/**
	 * @param date
	 * DDMMYYYY DATE VALIDATION
	 * It can validate the following three formats of dates:
	 * 20-07-1982
	 * 20/07/1982
	 * 20.07.1982
	 */
	public static boolean isAValidDDMMYYYYDate(String date)	{
		return Pattern.matches(regexDDMMYYYY, date);
	}
}

Originally posted 2011-05-17 20:46:12.

Share


Viewing all articles
Browse latest Browse all 12

Trending Articles