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:
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!