How to Validate Date with Regular Expression in Java


In this example we will show how to validate date with regular expression in Java.

Source Code

package com.beginner.examples;

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

public class ValidateDate {

	public static void main(String[] args) {
		String date1 = "2019-01-03";
		String date2 = "2019-02-29";
		String date3 = "2019-13-03";
		String date4 = "2019-06-31";
		String date5 = "2019-01-32";
		
		System.out.println(isDate(date1));  
		System.out.println(isDate(date2));  
		System.out.println(isDate(date3));  
		System.out.println(isDate(date4));  
		System.out.println(isDate(date5));
	}
	
	public static boolean isDate(String date){   
		String rexp = "^((d{2}(([02468][048])|([13579][26]))[-/s]?((((0?[13578])|(1[02]))[-/s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[-/s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[-/s]?((0?[1-9])|([1-2][0-9])))))|(d{2}(([02468][1235679])|([13579][01345789]))[-/s]?((((0?[13578])|(1[02]))[-/s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[-/s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[-/s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))";
		Pattern pat = Pattern.compile(rexp);    
		Matcher mat = pat.matcher(date);      
		boolean dateType = mat.matches();
		return dateType;  
	}

}

Output:

true
false
false
false
false

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments