The following code can be used to validate if a string contains a valid date information. The pattern of the date is defined by the java.text.SimpleDateFormat
object. When the date is not valid a java.text.ParseException
will be thrown.
package org.kodejava.text;
import java.text.SimpleDateFormat;
import java.text.ParseException;
public class DateValidation {
public static void main(String[] args) {
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
// Input to be parsed should strictly follow the defined date format
// above.
format.setLenient(false);
String date = "29/18/2021";
try {
format.parse(date);
} catch (ParseException e) {
System.out.println("Date " + date + " is not valid according to " +
format.toPattern() + " pattern.");
}
}
}
The result of the above date validation code is:
Date 29/18/2021 is not valid according to dd/MM/yyyy pattern.
Latest posts by Wayan (see all)
- How do I use Proxy class to configure HTTP and SOCKS proxies in Java? - March 27, 2025
- How do I retrieve network interface information using NetworkInterface in Java? - March 26, 2025
- How do I work with InetAddress to resolve IP addresses in Java? - March 25, 2025
When I tested this code, I found that it was accepting the input “22/10/20” which ideally it shouldn’t because the year is not a 4 digit number.