Check if a Java Date String is Valid or Not (Java 8)


To check if a date of type String is valid or not, you can create a array or a list of date format and iterate through them to check if it is valid or not.

Java Code:
package org.code2care.rabbitmq;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class JavaDateTimeValidator {

    public static void main(String[] args) {

        String inputDateString1 = "2023-06-23 11:30 AM";
        String inputDateString2 = "32-02-2023";

        //you can add your valid supported formats
        String[] dateFormatPatterns = {
                "yyyy/MM/dd",            // Example: 2023/06/30
                "dd/MM/yyyy",            // Example: 23/06/2023
                "MM/dd/yyyy",            // Example: 06/23/2023
                "yyyy-MM-dd HH:mm a",    // Example: 2023-06-30 11:30 AM
                "dd/MM/yyyy HH:mm:ss",   // Example: 23/06/2023 11:30:00
                "MM-dd-yyyy",            // Example: 06-30-2023
                "MMM dd, yyyy HH:mm:ss", // Example: Jun 23, 2023 11:30:00
                "dd MMMM yyyy",          // Example: 30 June 2023
                "hh:mm a",               // Example: 11:30 AM/PM
                "HH:mm:ss",              // Example: 11:30:00
                "hh:mm:ss a"             // Example: 11:30:00 AM/PM
        };

        String res1 = validateDateTimeString(inputDateString1, dateFormatPatterns);
        String res2 = validateDateTimeString(inputDateString2, dateFormatPatterns);

        System.out.println("The inputted date string  " + inputDateString1 + " is: " + res1);
        System.out.println("The inputted date string  " + inputDateString2 + " is: " + res2);
    }

    public static String validateDateTimeString(String dateTimeStr, String[] dateFormatPatterns) {

        for (String datePattern : dateFormatPatterns) {
            try {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern(datePattern);
                LocalDateTime.parse(dateTimeStr, formatter);
                return "valid";
            } catch (DateTimeParseException e) {
                // just continue
            }
        }
        return "invalid";
    }
}
Output:

The inputted date string 2023-06-23 11:30 AM is: valid
The inputted date string 32-02-2023 is: invalid

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap