Home >Java >javaTutorial >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!