×

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:

How to check valid date in Java

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:

How to check valid date in Java

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:

How to check valid date in Java

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:

How to check valid date in Java

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:

How to check valid date in Java

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:

How to check valid date in Java

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));

Related Topics

Difference between String, StringBuffer and StringBuilder in java

What is a string in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Convert JSON File to String in Java

Before understanding the conversion of JSON file to string, one must know about JSON. What is JSON? JSON stands for JavaScript Object Notation. It is an open standard format lightweight, text-based, and...

3 minutes read.

Java Integer rotateRight() method

The rotateRight() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value right by the specified number of bits. Syntax public...

1 minute read.

Mutable and Immutable in Java

Java is a programming language in which everything is treated as an object. Its procedures and functions are centred around objects because it is an object-oriented programming language. Mutable and...

6 minutes read.

Java Socket Programming

Java Socket Programming Socket programming is used for the communication between the applications, i.e., client and server running on different JRE may be connection-oriented or connectionless. The client program can be designed using the...

8 minutes read.

Java Math nextUp() Method

The nextUp() method of Math class returns the floating-point number adjacent to the argument in direction of the positive infinity. Syntax: public static double nextUp (double d)public static float nextUp (float f) Parameters: The...

2 minutes read.

Activity selection problem in Java

The activity selection problem is a multiple objective problem hat requires choosing non-conflicting tasks to complete within a specific amount of time from a list of tasks identified by a...

5 minutes read.

Java program to count the occurrences of each character

The count of each character is the frequency of the characters. For example, the given String is “Programming”. In the given string, the count of the characters ‘P’ -1, ’r’-2,...

6 minutes read.

Types of JDBC Drivers

JDBC Drivers: A piece of software known as JDBC Driver permits database communication between Java applications and the server. In order to communicate with our database server, JDBC drivers put into practice...

4 minutes read.

Java Math decrementExact() Method

The decrementExact() method of Math class returns the argument which is decremented by one, throwing an exception is the result overflows an int or long. Syntax: public static int decrementExact (int a) Parameters: The...

1 minute read.

Java Wrapper classes

Java Wrapper classes A wrapper class is a class whose object contains a primitive data type; moreover it provides a way to use primitive data type (int, boolean, etc.) as objects. Wrapper...

2 minutes read.

Fork Join in Java

Multithreaded processors are being introduced in new computer systems today. The operation is faster due to multicore CPUs. Therefore, it becomes essential for a programmer to leverage multithreaded processors effectively...

4 minutes read.

if-else Program in Java

if-else Program in Java The if-else program in Java controls which code snippet will execute. The if-else program is very basic and yet very important. Because it checks how well one...

19 minutes read.

Java Boolean toString() Method

The toString() method of Java Boolean class returns a String corresponding to this Boolean object. It returns a string value “true”, if the defined object is true else it returns...

2 minutes read.

Session Tracking in Java

When a series of requests from the same User (i.e., requests coming from the same browser) occurs over an extended period of time, servlets employ a mechanism known as session...

3 minutes read.

How to download Eclipse for Java

Introduction: We write a java program, and when we want to run it, we need software to run it. Eclipse is a kind of software used to execute a JavaFX...

3 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.

Java Transient

Java Transient In Java, Serialization is used to convert an object into a stream of the byte. The byte stream consists of the data of the instance as well as the...

3 minutes read.

Array Programs in Java

Array Programs in Java: An array is a data structure that stores similar elements in a contiguous memory location. In Java, an array is an object that stores the same...

7 minutes read.

How to Create an Object in Java

How to Create an Object in Java An object can be defined as a run time entity that contains the blue printof the class. It means that all the member functions...

5 minutes read.