×

How to check if date is valid in Java?

In this article, you will acknowledge about how to verify if a date is valid or not. For this you will learn the approach, you will be able to write a program that checks for the validation, and conclude if the given date is valid or not by the output produced by the program that you have learnt.

Since the symbol u stands for year and the symbol y stands for year-of-era, AD or BC, we choose u for the year format in DateTimeFormatter.

We use a single M for just the month and a single d for a day because we need to handle single or preceding zero types (1 or 01) for the month and day, respectively.

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 legal format, like MM/DD/YYYY.
  • The input's various components all fall inside a valid range.
  • The calendar's valid date is determined by the input.

The preceding is possible using regular expressions. Regular expressions, however, are complicated and prone to mistakes when handling different input formats and locations. Performance can suffer as a result.

Let us discuss a few examples to understand it in a better way

Example 1:

Consider a date in the format of dd/mm/yyyy

Input: 25/08/2001

Output: The given date is valid.

Explanation: The given date is valid because it exists in the calendar of the year 2001 year.

Example 2:

Consider a date in the format of dd/mm/yyyy

Input: 29/02/2022

Output: The given date is not valid

Explanation: The given date is not valid because it doesn’t exist according to the calendar of the year 2022.

Criteria

There are few criterions that must be followed when validating if the date is correct or not. They are:

  • Y, m, and d are within acceptable bounds.
  • Days of February are within the permitted range, while leap year is taken into account.
  • Months of 30 days are handled as days.

Let us implement an example program that can help in better understanding.

File name: DateValidation.java

DateValidation.java

//Java Program that checks if a given date is valid or not
package datevalidation;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Scanner;


public class DateValidation {


    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        
        System.out.println("Enter a date in dd/mm/yyyy format");
        
        String date = sc.next();
        
        if(dateValidation(date)==true)
            System.out.println("Date is valid");
        else
            System.out.println("Date is invalid");
               
    }
    
    private static boolean dateValidation(String date)
    {
      boolean status = false;


    if (checkDate(date)) {
      DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
      dateFormat.setLenient(false);
      try {
        dateFormat.parse(date);
        status = true;
      } catch (Exception e) {
        status = false;
      }
    }
    return status;
    }
    
    static boolean checkDate(String date) {
    String pattern = "(0?[1-9]|[12][0-9]|3[01])\\/(0?[1-9]|1[0-2])\\/([0-9]{4})";
    boolean flag = false;
    if (date.matches(pattern)) {
      flag = true;
    }
    return flag;


  }   
}

Output

Enter a date in dd/mm/yyyy format
25/08/2001
Date is Valid


Enter a date in dd/mm/yyyy format
16/08/2001
Date is Valid


Enter a date in dd/mm/yyyy format
29/02/2022
Date is Invalid

The code snippet above creates a DateFormat class object and passes a date format to the constructor.

By default, the setLenient() method returns true, which means it won't verify whether the date actually exists or not.

As a result, we set it to false in order for it to verify if the given date actually exists or not, in the check-date approach.

Other Approaches

When using ResolverStyle.LENIENT mode, the inaccurate date is advanced by the corresponding amount of days. Since there is no 31st day in a leap year, ResolverStyle.SMART mode (the standard) makes the sensible choice to maintain the date within the month and use February 29 as the last day. There is no such date, thus the ResolverStyle.STRICT mode raises an exception.

Based on our  situation and policies, all three of them are valid options. It appears that we prefer the stringent method to reject the incorrect date in your situation rather than amend it.


Related Topics

Object Oriented Programming (OOPs)

Since the dawn of earth, we have kept on evolving. The need for evaluation comes with the aim of improving the existing systems when something inappropriate is found for the...

5 minutes read.

How to resolve Illegal state exceptions in Java

What is IllegalStateException? When a method is called at the incorrect time, a runtime exception called an IllegalStateException is raised in Java. This exception is utilized to show that a method...

3 minutes read.

House Numbers in Java

In this section, we will discuss about house number in Java. It is a sum of cubes, each of which has a dimension of h + 1. There is a...

3 minutes read.

Trimorphic numbers in Java

Wondered what the Trimorphic number is!! In this article, you can learn about what a Trimorphic number is referred to as and how to find whether a number is trimorphic...

3 minutes read.

Manachers Algorithm in Java

Here, we'll go over the four scenarios once more in an effort to approach them differently and use the same strategy. The values of (centerRightPosition - currentRightPosition) and LPS length at...

3 minutes read.

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.

Basic Terms in Multithreading

To understand the terms of multithreading, we must have knowledge about concurrency, processes, and threads. Concurrency The concurrency stands for performing multiple tasks at the same time. In the process communication, the operating system permits the process...

8 minutes read.

How Many Ways to Create Objects in Java

Introduction Java comes under the category of object-oriented programming languages. Since it is object-oriented, everything in Java is considered an object. Java is a diverse programming language that is designed to...

6 minutes read.

Java Polymorphism

The process of representing one form in multiple forms is known as Polymorphism. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means...

5 minutes read.

Java vs Golang

Java Java is both a programming language and a platform. Java is a high-level, dependable, object-oriented, and secure programming language. Java was developed in 1995 by Sun Microsystems, which is now an...

4 minutes read.

Missing Number in an Arithmetic Progression in Java

Given an array that shows the elements of an orderly arithmetic progression. Find the missing number to complete the succession of elements. Example:  Input: a [ ] = {2 , 4 , 6...

3 minutes read.

Sorting Algorithms in Java

Sorting Algorithms in Java Sorting is the technique that puts the elements of an array or list either in descending or ascending order. For example, take an array A, whose elements...

3 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 Network Programming (Socket Programming in Java)

JAVA NETWORK Network programming is used to execute programs across multiple machines that are connected by a network. The java.net package contains a collection of classes and interfaces that provide this...

3 minutes read.

HttpURLConnection

HttpURLConnection Protocol It is a standard set of rules that allow electronic devices to communicate with each other. The http protocol The http protocol is for data communication, distributing, collaborating, hypermedia information systems, on the World Wide...

5 minutes read.

Matrix Multiplication Program in Java

Matrix Multiplication Program in Java The matrix multiplication program in Java is the continuation of the matrix program in Java that we have already discussed earlier. In this section, we will...

3 minutes read.

Java Iterator

When iterating through, traversing, or retrieving the individual elements of a Collection or Flow object, a Java Cursor is leveraged as an iterator. In Java, there exist three types of...

4 minutes read.

Quick Sort in Java

Quick Sort in Java Like merge sort, quick sort also uses the divide and conquer approach to sort the given array or list. In quick sort, the sorting of an array...

6 minutes read.

Java Math log10() Method

The log10() method of Math class returns the base 10 logarithmic value for the specified double argument. Syntax: public static double log10(double a) Parameters: The parameter ‘a’ represents a double value. Return Value: The log10() method...

2 minutes read.

Java Integer hashCode() method

The hashCode()  method of Java Integer class returns a hash code for this Integer.  Syntax public int hashCode() public static int hashCode(int value)  Parameters The parameter ‘value’ represents a value whose hash code...

1 minute read.