Tuesday, April 14, 2015

Validate Date Format Using Regular Expressions in JAVA

As such there is no API in java to validate the format of Date String (I didn't found any). I have had a requirement for the same in my code. Accomplished it using Regular Expressions. Thought of sharing my piece of code with the world residing on other side of my laptop screen, may be useful for someone.

Here is the code:

// Check the Date format to be MM/dd/yyyy
    private boolean validateDateFormat(String date){
        StringBuffer sBuffer = new StringBuffer(date);
        String mon;
        String dd;
        String year;

        // Store the Date in String Buffer and Break down the date
        mon = sBuffer.substring(0,2);
        dd = sBuffer.substring(3,5);
        year = sBuffer.substring(6,10);
        System.out.println("DD: "+ dd + " Mon: "+ mon + " Year: "+ year);

        // Validating Date Format for Tunr In Date and Live Date to be MM/dd/yyyy
        if(mon.matches("0[1-9]|1[0-2]") && dd.matches("0[1-9]|[12][0-9]|3[01]")
                && year.matches("(19|20)\\d\\d")){
            return true;
            return false;

Thanks for reading folks. Do share your thoughts and comments.

Happy Learning :)

Vaneesh Behl