In this tutorial, we will see how to validate a date to check whether it is in valid format or not.
Java Date Validation: Checks whether a Date is valid or not
In this example, we are checking whether a given date is valid or not. In the method validateJavaDate(String)
we have specified the date format as “MM/dd/yyyy” that’s why only the date passed in this format is shown as valid in the output. You can specify any format of your choice and then check other formats against it.
import java.text.SimpleDateFormat; import java.util.Date; import java.text.ParseException; public class Example{ public static boolean validateJavaDate(String strDate) { /* Check if date is 'null' */ if (strDate.trim().equals("")) { return true; } /* Date is not 'null' */ else { /* * Set preferred date format, * For example MM-dd-yyyy, MM.dd.yyyy,dd.MM.yyyy etc.*/ SimpleDateFormat sdfrmt = new SimpleDateFormat("MM/dd/yyyy"); sdfrmt.setLenient(false); /* Create Date object * parse the string into date */ try { Date javaDate = sdfrmt.parse(strDate); System.out.println(strDate+" is valid date format"); } /* Date format is invalid */ catch (ParseException e) { System.out.println(strDate+" is Invalid Date format"); return false; } /* Return true if date format is valid */ return true; } } public static void main(String args[]){ validateJavaDate("12/29/2016"); validateJavaDate("12-29-2016"); validateJavaDate("12,29,2016"); } }
Output:
12/29/2016 is valid date format 12-29-2016 is Invalid Date format 12,29,2016 is Invalid Date format
Leave a Reply