Ask Your Question
0

What is the process to verify a date in Java?

asked 2021-12-14 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-07-20 07:00:00 +0000

plato gravatar image

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.");
    }
  }
}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-12-14 11:00:00 +0000

Seen: 10 times

Last updated: Jul 20 '22