Home >Java >javaTutorial >How to Validate a Date's Legitimacy in Java?

How to Validate a Date's Legitimacy in Java?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-27 02:30:14427browse

How to Validate a Date's Legitimacy in Java?

How to Verify Date Validity in Java

Despite the discontinuation of the traditional Date object creation method, Java provides a solution for validating the legitimacy of dates using a lenient calendar.

Question: How to determine whether a date (specified as day, month, and year) is legitimate? For instance, 2008-02-31 would be invalid.

Answer:

The critical step is disabling the lenient setting of the date formatter:

df.setLenient(false);

This simple adjustment is sufficient for basic date validation scenarios. If you require more robust functionality or prefer alternative libraries, refer to the answer provided by "tardate":

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;
    }
}

The above is the detailed content of How to Validate a Date's Legitimacy in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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