VOOZH about

URL: https://www.geeksforgeeks.org/java/validate-a-date-input-from-a-user-to-ensure-in-a-specific-format-in-java/

⇱ How to Validate Date Input from User in Specific Formats in Java? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Validate Date Input from User in Specific Formats in Java?

Last Updated : 15 Feb, 2024

In Java, validating user-provided dates to ensure a specific format is very important for maintaining data integrity and application functionality. Mainly two commonly used approaches are SimpleDateFormat class and DateTimeFormatter class, which validates the expected date format and parses the user input.

In this article, we will learn how to validate a date input into a specific format in Java.

Methods to Validate a Date Input into a Specific Format

There are mainly two ways to validate a date input to ensure it's in a specific format in Java.

  • Using SimpleDateFormat
  • Using java.time.DateTimeFormatter

Below is the code implementation of these two approaches.

Program to Validate a Date Input to Ensure it is in a Specific Format in Java

Below are the two methods implementations to validate a date input to ensure it in a specific format.

Method 1: Using SimpleDateFormat

By using SimpleDateFormat we will validate the date format.


Output
Valid date format: 09-02-2024

Explanation of the above Program:

In the above Program,

  • We have defined the expected date format as "dd-MM-yyyy" using the SimpleDateFormat class.
  • We set the lenient property of the dateFormat object to false to enforce strict date parsing.
  • The input date string is "09-02-2024".
  • We attempt to parse the input string into a Date object using the specified format in a try-catch block.
  • If parsing is successful, we print the valid date format. If parsing fails (due to an invalid format), a ParseException is caught, and we print an error message indicating the expected date format (yyyy-MM-dd).

Method 2: Using java.time.DateTimeFormatter

By using DateTimeFormatter class we will validate the date format.


Output
Invalid date format: 2024-02-09

Explanation of the above Program:

In the above Program,

  • We have defined the date format as "dd/MM/yyyy".
  • We have created a DateTimeFormatter object named formatter using the DateTimeFormatter.ofPattern method.
  • Then we input the date string.
  • We attempt to parse the input string into a LocalDate object using the specified formatter in a try-catch block.
  • If parsing is successful, we print the valid date. If parsing fails (due to an invalid format), an exception is caught, and we print an error message indicating the invalid date format.
Comment