Skip to content
Advertisement

How to sanity check a date in Java

I find it curious that the most obvious way to create Date objects in Java has been deprecated and appears to have been “substituted” with a not so obvious to use lenient calendar.

How do you check that a date, given as a combination of day, month, and year, is a valid date?

For instance, 2008-02-31 (as in yyyy-mm-dd) would be an invalid date.

Advertisement

Answer

The current way is to use the calendar class. It has the setLenient method that will validate the date and throw and exception if it is out of range as in your example.

Forgot to add: If you get a calendar instance and set the time using your date, this is how you get the validation.

Calendar cal = Calendar.getInstance();
cal.setLenient(false);
cal.setTime(yourDate);
try {
    cal.getTime();
}
catch (Exception e) {
  System.out.println("Invalid date");
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement