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; } }
Employing this method, the validity of a date can be checked as follows:
if (isDateValid("2008-02-31")) { // Invalid date } else { // Valid date }
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!