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.