×

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

Memory Areas in Java

Let’s have a look at how memory management in Java works. We will be going to discuss how the objects get destroyed, the working of a garbage collector, and things...

5 minutes read.

Java Math max() Method

The max() method of Math class returns the greater of two arguments. The arguments can be of double, float, int or long data type. Syntax: public static double max(double a, double b)public...

2 minutes read.

How to run Java Program?

How to run Java Program In this section, we will learn how to write, compile and run a Java program in Command Promptusing notepad. In order to run a Java program, we...

2 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.

Java Math ceil() Method

The ceil() method of Math class returns the smallest double value which is closest to negative infinity and is greater than or equal to the argument. Syntax: public static double ceil(double a) Parameters: The...

2 minutes read.

Dutch National Flag Problem in Java

Dutch National Flag (DNF) is a programming issue that Edsger Dijkstra put up. The white, red, and blue hues make up the Dutch flag. The goal is to haphazardly set...

6 minutes read.

Lazy Propagation in Segment Tree in Java

The topic of segment trees in Java is continued by the topic of sluggish propagation in segment trees. It is suggested that readers first read through the section tree topic....

4 minutes read.

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

Java ArrayList

Java ArrayList Class A Java ArrayList class is a dynamic array which is used to store the elements. It is a part of collection framework. It implements the List Interface and inherits the...

12 minutes read.

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...

4 minutes read.

How to Convert Decimal to Binary in Java

How to Convert Decimal to Binary in Java There are two methods to convert Decimal to Binary. Using toBinaryString() method Using user-defined logic Using Integer.toBinaryString() The toBinaryString() is a static method of Integer...

2 minutes read.

Advanced Java Viva Questions

One of the more difficult languages available now is Java. Currently, 10 thousand developers worldwide use the programming language, which is rising daily. So, if you're a Java developer, an aspiring...

9 minutes read.

Java Anon Proxy

The Java Anon Proxy (JAP), also known as JonDonym, is a proxy system designed to enable Web browsing with revocable (the use of or publication under a pseudonym, a false...

4 minutes read.

Practical Number in Java

In this tutorial, we will understand what is meant by practical numbers. We will understand it throughthe aid of examples and implementation in a java programming language. The practical numbers...

5 minutes read.

Java Map Example

In Java, the Map is an interface that is used mainly to denote key and value pairs. The central concept and theme of this mapping in the java collection framework...

4 minutes read.

Java Stringjoiner Class

StringJoiner is a class which is used to construct a sequence of characters which are separated by a delimiter. Optionally, it starts with a provided prefix and ended with the...

5 minutes read.

Thread Synchronization in Java

In Java, the smallest processing component is a thread, which is a small subprocess. It follows a different course of action. Threads are autonomous. If an exception occurs in one thread,...

6 minutes read.

String Concatenation in Java

In Java, it gathers a new String that combines several strings. Following are the manners to concatenate strings in Java: By + (String concatenation) operatorBy concat() method By + (String concatenation) operator Java...

4 minutes read.

Java String Concatenation

Java String Concatenation Java programming provide a way to combine multiple strings into a single string. It is called as String Concatenation. There are different ways to concatenate two or more...

4 minutes read.

Minimum Window Subsequence in Java

In this article, you will be very well acknowledged about the minimum window subsequence, what is the approach and how it is implemented. The example program is also executed and...

4 minutes read.