Home > Java > javaTutorial > How Can I Validate Dates in Java Using SimpleDateFormat?

How Can I Validate Dates in Java Using SimpleDateFormat?

Patricia Arquette
Release: 2024-12-17 01:14:25
Original
205 people have browsed it

How Can I Validate Dates in Java Using SimpleDateFormat?

Validating Dates in Java

In Java, the commonly employed method for creating Date objects, utilizing the Date class, has been marked as deprecated. While the lenient calendar appears to be its replacement, its usage may not be immediately apparent. This article addresses how to effectively ascertain the validity of a date represented as a combination of day, month, and year.

The provided solution leverages the SimpleDateFormat class and the key setting of df.setLenient(false);. This setting ensures a strict parsing of dates, invalidating any entries containing inconsistencies, such as "2008-02-31."

To implement this solution, a static method called isDateValid() can be defined:

private static final String DATE_FORMAT = "dd-MM-yyyy";

public static boolean isDateValid(String date) {
  try {
    DateFormat df = new SimpleDateFormat(DATE_FORMAT);
    df.setLenient(false);
    df.parse(date);
    return true;
  } catch (ParseException e) {
    return false;
  }
}
Copy after login

Employing this method, the validity of a date can be checked as follows:

if (isDateValid("2008-02-31")) {
  // Invalid date
} else {
  // Valid date
}
Copy after login

The above is the detailed content of How Can I Validate Dates in Java Using SimpleDateFormat?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template