Avoiding Date Pitfalls: Sanity Checking Dates in Java
The default behavior of Java's date and calendar classes can be problematic when handling dates. To ensure the validity of dates, it's essential to properly sanity check them.
Question:
How can we validate a date given a combination of day, month, and year, ensuring it's a valid date? For example, checking if 2008-02-31 is a valid date.
Solution:
To sanity check a date, we can use the SimpleDateFormat class:
final static String DATE_FORMAT = "dd-MM-yyyy"; public static boolean isDateValid(String date) { try { DateFormat df = new SimpleDateFormat(DATE_FORMAT); // Set lenient to false for strict date validation df.setLenient(false); df.parse(date); return true; } catch (ParseException e) { return false; } }
By setting df.setLenient(false), the parser strictly adheres to date formatting rules, enabling us to accurately determine whether a date is valid or not.
The above is the detailed content of How to Validate Dates in Java and Avoid Common Pitfalls?. For more information, please follow other related articles on the PHP Chinese website!