How to Check If Date Is Valid in Java


In this example we will show two methods to check if date is valid in Java.

Source Code

1) Using java.text.SimpleDateFormat

package com.beginner.examples;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

public class DateValidExample1 {

    public static void main(String[] args) {

    	DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); 
    	df.setLenient(false);
    	String str ="2019-02-29";
    	try
    	{
    		df.parse(str);
    		System.out.println("The date "+str+" is valid.");
    	}
    	catch(Exception e)
    	{
    		System.out.println("The date "+str+" is invalid.");
    	}
    }
}

Output:

The date 2019-02-29 is invalid.

2) Using java.util.regex.Pattern

package com.beginner.examples;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;  
import java.util.regex.Pattern;

public class DateValidExample2 {

    public static void main(String[] args) {

    	String str ="2019-02-29";
    	if(isValid(str))
    	{
    		System.out.println("The date "+str+" is valid.");
    	}
    	else
    	{
    		System.out.println("The date "+str+" is invalid.");
    	}
    }
    public static boolean isValid(String str) {  
        String p1 = "d{4}-d{2}-d{2}";  
        String p2 = "^((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 p = Pattern.compile(p1);  
        Matcher match = p.matcher(str);  
        if (match.matches()) 
        {  
            p = Pattern.compile(p2);  
            match = p.matcher(str);  
            return match.matches();  
        } 
        else 
        {  
            return false;  
        }
    }
}

Output:

The date 2019-02-29 is invalid.

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments