×

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

Level order Traversal of a Binary Tree in Java

In Java, a level order traversal of a tree structure is also referred to as the breadth-first traversal of the binary tree. Regarding the subsequent binary tree: Level order traversal is as...

5 minutes read.

Convert List to String in Java

We occasionally need to create a string from a list of characters. Since a string is only a collection of characters, a character array can be converted into a string....

6 minutes read.

Various operations on the Queue using Stack in Java

The Java Collections Framework's core data structures are the Stack and Queue. They are used to store and retrieve identical data in a presentation sequence. These two linear data structures...

7 minutes read.

Static class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM is mostly...

7 minutes read.

Constructor Chaining and Constructor Overloading in Java

Constructor Chaining Constructor chaining and constructor overloading are two confusing terms. Let's first understand constructor chaining.Constructor chaining is the process of calling one constructor from another constructor using the same object....

2 minutes read.

Java FileOutputStream

What is FileOutputStream?When we need raw stream data written into a file, we need to look for another option: FileOutputStream. It is used when the file's data is byte-oriented. It comes under...

4 minutes read.

Java time local date

Java: Java is one of the programming language which is object oriented. It consists of many features such as robust, simple, architecture neutral, dynamic, distributed, multi threaded, portable etc. The main feature...

3 minutes read.

How to Convert String to Object in Java

How to Convert String to Object in Java The Object is the super class of all classes. So you can assign a string to Object directly. There are two methods to...

3 minutes read.

Determine the Upper Bound of a Two-Dimensional Array in Java

Multi-Dimensional Array Multi-faceted exhibits in Java are regular and can be named various clusters. Information in a two-layered bunch in Java is put away in 2D even structure. A two-layered collection...

3 minutes read.

Java Math atan2() Method

The atan2() method of Math class returns an angle theta from the conversion of rectangular coordinates to polar coordinates. Syntax: public static double atan2(double y, double x) Parameters: The parameter ‘y’ represents the ordinate...

3 minutes read.

Java TreeMap

TreeMap in Java with Example Java TreeMap implements the NavigableMap interface. It extends Map Interface. Java TreeMap is based on the red-black Tree implementation. It stores the key-value pair in sorted...

7 minutes read.

Java String toLowerCase() methods

Java String toLowerCase() method is used to convert all the characters of the String into lower case. Syntax: public String toLowerCase()              public String toLowerCase(Locale locale) Returns: It returns Lower...

1 minute read.

Java 16

Java 16 is the most recent short-term incremental release, based on Java 15, and it was released on March 16, 2021. Records and sealed classes are just two of the...

11 minutes read.

ArrayList vs Vector in Java

ArrayList Vs. Vector in Java In Java, the two classes ArrayList and Vector both are associated with Java Collections Framework. Both classes implement java.util.List interface. Even so, these classes have noticeable...

4 minutes read.

StringBuilder in Java

StringBuilder in Java Java StringBuilder class is introduced since JDK 1.5. The StringBuilder class is mainly used to create modifiable or mutable strings. Note that the StringBuilder class is not synchronized....

7 minutes read.

Java Swings

Swing is a Java Foundation Class library and an extension to the Abstract Window Toolkit (AWT) (JFC).As compared to AWT, Swing has significantly better functionality, new components, increased component features,...

9 minutes read.

Perfect Number in Java

The concept of a perfect number in Java will be defined in this chapter, along with creating Program code that determine whether a specific number is perfect or not. Additionally,...

4 minutes read.

Compare time in java

Introduction: This article discusses how to compare time in java. Maximum of the time we need to examine the date and datetime items. Date comparisons are vital if you want to...

3 minutes read.

Star Pattern Programs in Java

Star Pattern Programs in Java The star pattern programs in Java is the part of pattern programs in Java, which we discussed earlier. Right Triangle Star Pattern Filename: StarPatternExample.java public class StarPatternExample {              public static void...

4 minutes read.

Fibodiv Number in Java

Before understanding the concept of the fibodiv number, one should realize what the Fibonacci number is. What are Fibonacci Numbers? The Fibonacci sequence of whole numbers is composed of the numbers 0,...

5 minutes read.