java

Java Program to Check Whether a Date is Valid or Not

In this tutorial, we are going to see how to write a java program to check whether a date is valid or not by handling the ParseException.
 

Java Program to Check Whether a Date is Valid or Not:
import java.text.*;
import java.util.*;

public class Main {
   public static boolean check(String date)
   {
	    // Set the preferred date format
	    SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
	    format.setLenient(false);
	    try
	    {
	        Date d = format.parse(date); 
	        System.out.println(date+" is a valid date");
	    }
	    // Invalid date
	    catch (ParseException e)
	    {
	        System.out.println(date+" is an invalid date");
	        return false;
	    }
	    // Returns true if the date is valid
	    return true;
   }
   
   public static void main(String args[]){
		check("07/25/2020");
		check("07/25/0000");
		check("07,25,2020");
   }
}

Output:

07/25/2020 is a valid date
07/25/0000 is an invalid date
07,25,2020 is an invalid date
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *