Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The process to verify a date in Java involves the following steps:

  1. First, create a Date object using the SimpleDateFormat class. This allows you to parse a date string into a Date object.

  2. Once you have the Date object, you can check whether it is valid by attempting to format it output using SimpleDateFormat again. If the format fails and throws an exception, then the date is not a valid date.

  3. You can also check whether the date falls within a particular range by creating two Date objects representing the start and end dates of the range, and then checking whether the date you are verifying falls between those two dates using the compareTo() method.

Here is some sample code that demonstrates the process:

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateVerifier {

  public static void main(String[] args) {
    verifyDate("2019-07-06"); // Valid date
    verifyDate("2020-13-01"); // Invalid date, month can't be 13
    verifyDate("2021-09-31"); // Invalid date, September has only 30 days
  }

  public static void verifyDate(String dateString) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    try {
      // Try to parse the date string into a Date object
      Date date = dateFormat.parse(dateString);

      // Check if the parsed date is a valid date by attempting to format it again
      String formattedDate = dateFormat.format(date);

      if (!formattedDate.equals(dateString)) {
        System.out.println(dateString + " is not a valid date.");
      } else {
        System.out.println(dateString + " is a valid date.");
      }

      // Check if the date falls within a particular range
      Date startDate = dateFormat.parse("2020-01-01");
      Date endDate = dateFormat.parse("2021-12-31");

      if (date.compareTo(startDate) >= 0 && date.compareTo(endDate) <= 0) {
        System.out.println(dateString + " falls within the range " + startDate + " - " + endDate);
      } else {
        System.out.println(dateString + " does not fall within the range " + startDate + " - " + endDate);
      }

    } catch (Exception e) {
      System.out.println(dateString + " is not a valid date.");
    }
  }
}