How to check valid date in Java?
Every time we get data for any application, we must first ensure that it is accurate before continuing with any further processing.
We might have to confirm the following while dealing with date inputs:
- The date is present in the input in a suitable format, such as MM/DD/YYYY.
- The various components of the input are inside a valid range.
- The input returns a calendar date that is appropriate.
We could accomplish the above using regular expressions. However, regular expressions are difficult and susceptible to error when handling different input formats and locales. They may also cause performance to suffer.
We'll go over various approaches to flexible, reliable, and effective date validation implementation.
public interface DateValidator {
boolean isValid(String dateStr);
}
Using the DateFormat to validate
Since its inception, Java has included date formatting and parsing capabilities. The SimpleDateFormat implementation of the DateFormat abstract class contains this capability.
The example that follows shows how to use the String class's matches function to determine whether or not the date is formatted correctly.
DateFormat.java
public class DateFormat {
public static void main(String[] argv) {
boolean isDate = false;
String date1 = "25-11-1927";
String date2 = "08/11/2022";
String datePattern = "\\d{1,2}-\\d{1,2}-\\d{4}";
isDate = date1.matches(datePattern);
System.out.println("Date :"+ date1+": relates to this date Pattern:"+datePattern+"Ans:"+isDate);
isDate = date2.matches(datePattern);
System.out.println("Date :"+ date2+": relates to this date Pattern:"+datePattern+"Ans:"+isDate);
}
}
Output:

The example that follows shows how to determine whether a date is formatted correctly.
DateFomat.java
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DateFormat {
public static void main(String args[]) {
List dates = new ArrayList();
dates.add("25/11/2000");
dates.add("25/12/2001");
dates.add("12/12/80");
dates.add("05/02/1990");
String regex = "^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$";
Pattern pattern = Pattern.compile(regex);
for(Object date : dates) {
Matcher matcher = pattern.matcher((CharSequence) date);
System.out.println(date +" : "+ matcher.matches());
}
}
}
Output:

Use LocalDate to validate.
The LocalDate class, which represents a date without a time component, was added. This class is thread-safe and immutable.
In order to parse dates, LocalDate has two static methods, each of which uses a DateTimeFormatter:
Let's implement date validation using the parse method:
public class DateValidatorUsingLocalDate implements DateValidator {
private DateTimeFormatter dateFormatter;
public DateValidatorUsingLocalDate(DateTimeFormatter dateFormatter) {
this.dateFormatter = dateFormatter;
}
@Override
public boolean isValid(String dateStr) {
try {
LocalDate.parse(dateStr, this.dateFormatter);
} catch (DateTimeParseException e) {
return false;
}
return true;
}
}
Let's further provide a unit test for this usage:
DateTimeFormatter dateFormatter = DateTimeFormatter.BASIC_ISO_DATE;
DateValidator validator = new DateValidatorUsingLocalDate(dateFormatter);
assertTrue(validator.isValid("20220725"));
assertFalse(validator.isValid("19420230"));
LocalDateProgram.java
import java.time.LocalDate;
public class LocalDateProgram {
public static void main(String[] args) {
LocalDate date = LocalDate.now();
LocalDate yesterday = date.minusDays(1);
LocalDate tomorrow = yesterday.plusDays(2);
System.out.println("Present date: "+date);
System.out.println("Past date: "+yesterday);
System.out.println("Future date: "+tomorrow);
}
}
Output:

LocalDateProgram2.java
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class LocalDateProgram2
{
public static void main(String ar[])
{
// LocalDate to String Conversion
// Section 1
LocalDate d1 = LocalDate.now();
String d1Str = d1.format(DateTimeFormatter.ISO_DATE);
System.out.println("Date1 in string : " + d1Str);
// Section 2
LocalDate d2 = LocalDate.of(2072, 05, 01);
String d2Str = d2.format(DateTimeFormatter.ISO_DATE);
System.out.println("Date2 in string : " + d2Str);
// Section 3
LocalDate d3 = LocalDate.of(1942, 10, 31);
String d3Str = d3.format(DateTimeFormatter.ISO_DATE);
System.out.println("Date3 in string : " + d3Str);
}
}
Output:

LocalDateProgram3.java
import java.time.*;
public class LocalDateProgram3 {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2022, 11, 25);
LocalDateTime datetime = date.atTime(10,45,19);
System.out.println(datetime);
}
}
Ouput:

Use DateTimeFormatter to validate
A text is evaluated twice by DateTimeFormatter.
Phase 1: involves processing the text according to the setup into different date and time fields.
Phase 2: The processed fields are resolved into a date and/or time object.
ResolverStyle determines phase 2 of the resolution process. There are three potential values for this enum:
- LENIENT: leniently resolves dates and times
- SMART: intelligently resolves dates and times
- STRICT: strictly resolves dates and times
Dateisvalidornot.java
// Java programme to determine whether a date is
// valid or not.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Dateisvalidornot {
// if d is in format, it returns true.
// /dd/mm/yyyy
public static boolean isValidDate(String d)
{
String regex = "^(1[0-2]|0[1-9])/(3[01]"
+ "|[12][0-9]|0[1-9])/[0-9]{4}$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher((CharSequence)d);
return matcher.matches();
}
public static void main(String args[])
{
System.out.println(isValidDate("10/12/2022"));
System.out.println(isValidDate("27/08/22"));
}
}
Ouput:

Use the Apache Commons Validator to verify
A framework for validation is provided by the Apache Commons project. This includes procedures for validating date, time, numbers, currencies, IP addresses, emails, and URLs.
Let's examine the GenericValidator class, which contains several ways to determine whether a String includes a valid date:
public static boolean isDate(String value, Locale locale)
public static boolean isDate(String value,String datePattern, boolean strict)
Let's add the commons-validator Maven dependency to our project so that we may utilise the library:
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.6</version>
</dependency>
Let's now verify dates using the GenericValidator class:
assertTrue(GenericValidator.isDate("2019-02-28", "yyyy-MM-dd", true));
assertFalse(GenericValidator.isDate("2019-02-29", "yyyy-MM-dd", true));