Validating date String in Java can be tricky as you may not know which date format you are dealing with, so the best way can be to create a list of date formats that you support and iterate through it.
List of Some Valid Date Formats:
- yyyy-MM-dd
- MM/dd/yyyy
- dd-MM-yyyy
- yyyy/MM/dd
- MMMM dd, yyyy
- dd MMM yyyy
- yyyy-MM-dd HH:mm:ss
- MM/dd/yyyy HH:mm:ss
- dd-MM-yyyy HH:mm:ss
- yyyy/MM/dd HH:mm:ss
- MMMM dd, yyyy HH:mm:ss
- dd MMM yyyy HH:mm:ss
- EEE, d MMM yyyy HH:mm:ss Z
- yyyy-MM-dd'T'HH:mm:ss
- MM/dd/yyyy'T'HH:mm:ss
- dd-MM-yyyy'T'HH:mm:ss
- yyyy/MM/dd'T'HH:mm:ss
- MMMM dd, yyyy'T'HH:mm:ss
- dd MMM yyyy'T'HH:mm:ss
- EEE, d MMM yyyy'T'HH:mm:ss Z
- yyyy-MM-dd'T'HH:mm:ss.SSS
- MM/dd/yyyy'T'HH:mm:ss.SSS
- dd-MM-yyyy'T'HH:mm:ss.SSS
- yyyy/MM/dd'T'HH:mm:ss.SSS
- MMMM dd, yyyy'T'HH:mm:ss.SSS
- dd MMM yyyy'T'HH:mm:ss.SSS
- EEE, d MMM yyyy'T'HH:mm:ss.SSS Z
- yyyy-MM-dd'T'HH:mm:ss.SSSSSS
- MM/dd/yyyy'T'HH:mm:ss.SSSSSS
- dd-MM-yyyy'T'HH:mm:ss.SSSSSS
Example: Java 7 or before
package org.code2care.examples;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ValidateDateExample {
public static void main(String[] args) {
String dateStr = "2023-12-25";
//Add your valid date format list here
String[] validFormats = {
"yyyy-MM-dd",
"MM/dd/yyyy",
"dd-MM-yyyy",
"yyyy/MM/dd",
"MMMM dd, yyyy",
"dd MMM yyyy"
};
if (isValidDateFormat(dateStr, validFormats)) {
System.out.println("Date format is valid.");
} else {
System.out.println("Date format is not valid.");
}
}
public static boolean isValidDateFormat(String dateStr, String[] validFormats) {
for (String format : validFormats) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setLenient(false);
try {
Date date = sdf.parse(dateStr);
if (date != null) {
return true;
}
} catch (ParseException e) {
// Parsing failed, try the next format
}
}
// None of the formats resulted in a valid date
return false;
}
}
Example: Java 8 or above
package org.code2care.examples;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Arrays;
public class ValidateDateFormat {
public static void main(String[] args) {
String dateStr = "2023-July-25";
String[] validFormats = {
"yyyy-MM-dd",
"MM/dd/yyyy",
"dd-MM-yyyy",
"yyyy/MM/dd",
"MMMM dd, yyyy",
"dd MMM yyyy",
"yyyy-MMMM-dd"
};
boolean isValid = Arrays.stream(validFormats)
.anyMatch(format -> isValidDateFormat(dateStr, format));
if (isValid) {
System.out.println("Date format is valid.");
} else {
System.out.println("Date format is not valid.");
}
}
public static boolean isValidDateFormat(String dateStr, String format) {
try {
DateTimeFormatter.ofPattern(format).parse(dateStr);
return true;
} catch (DateTimeParseException e) {
return false;
}
}
}
Output:
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
More Posts related to Java,
- Get the current timestamp in Java
- Java Stream with Multiple Filters Example
- Java SE JDBC with Prepared Statement Parameterized Select Example
- Fix: UnsupportedClassVersionError: Unsupported major.minor version 63.0
- [Fix] Java Exception with Lambda - Cannot invoke because object is null
- 7 deadly java.lang.OutOfMemoryError in Java Programming
- How to Calculate the SHA Hash Value of a File in Java
- Java JDBC Connection with Database using SSL (https) URL
- How to Add/Subtract Days to the Current Date in Java
- Create Nested Directories using Java Code
- Spring Boot: JDBCTemplate BatchUpdate Update Query Example
- What is CA FE BA BE 00 00 00 3D in Java Class Bytecode
- Save Java Object as JSON file using Jackson Library
- Adding Custom ASCII Text Banner in Spring Boot Application
- [Fix] Java: Type argument cannot be of primitive type generics
- List of New Features in Java 11 (JEPs)
- Java: How to Add two Maps with example
- Java JDBC Transition Management using PreparedStatement Examples
- Understanding and Handling NullPointerException in Java: Tips and Tricks for Effective Debugging
- Steps of working with Stored Procedures using JDBCTemplate Spring Boot
- Java 8 java.util.Function and BiFunction Examples
- The Motivation Behind Generics in Java Programming
- Get Current Local Date and Time using Java 8 DateTime API
- Java: Convert Char to ASCII
- Deep Dive: Why avoid java.util.Date and Calendar Classes
More Posts:
- How to do a Print Screen on Windows 11 to Screencapture - Windows
- Where is Maven .m2 local repository located on Mac - HowTos
- Java: Convert String to InputStream - Java
- JSON Nest Objects Example: JSON Tutorial - Json-Tutorial
- How to clear Microsoft Teams Cache on Mac (macOS) - Teams
- Python: How to create a Dictionary of Lists with Examples - Python
- Android Shared Preferences API tutorial - Android
- How to Export a PowerShell Script/Cmdlet Output to a Text File - Powershell