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;
    }
    else{
        return false;
    }
}







Feel free to ask queries or share your thoughts in comments or email me. Happy Coding :)

Blog Author: Vaneesh Behl

Join Telegram channel of this blog at https://t.me/techlisticspace

Comments

Popular Posts

Top 10 Demo Websites to Practice Selenium Webdriver Online

Future of Selenium Automation Testing as a Career Option

How to learn Selenium Webdriver on your own online

Selenium WebDriver - Take Screenshot and Partial Screenshot Commands

Selenium Webdriver - Overview & Features