MENU

Java Date validity/existence check

TOC

Java DateValidity and existence check of Calendar.setLenient()

Javaindicates certainty, emphasis, etc.Date validity/existence checkThe following is a sample program that performs
Checks if the specified date string (yyyy/MM/dd or yyyy-MM-dd) exists on the calendar.

DateFormatClasssetLenient()to be false, date parsing can be performed strictly. (*DateFormat class internally uses thesetLenient() in java.util.Calendar classcall.)
This method of checking is based on the fact that calling the parse() method with an invalid or nonexistent date will result in a ParseException.


sample program

/**
 * Performs a date validity check.
 * Returns whether the given date string (yyyy/MM/dd or yyyy-MM-dd)
 * Returns whether the given date string (yyyy/MM/dd or yyyy-MM-dd) exists in the calendar.
 * @param strDate String to be checked.
 * @return true if the date exists.
 */
public static boolean checkDate(String strDate) {
    if (strDate == null || strDate.length() ! = 10) {
        throw new IllegalArgumentException(
                "The argument string ["+ strDate +"]" +
                "]" is invalid.") ;
    }
    strDate = strDate.replace('-', '/');
    DateFormat format = DateFormat.getDateInstance();
    // Set whether date/time parsing is strictly performed or not.
    format.setLenient(false);
    try {
        format.parse(strDate);
        return true;
    } catch (Exception e) {
        return false; }
    }
}

Execution Result

◆Example of Execution

public static void main(String[] args) {
    System.out.println(checkDate("2007-01-01"));
    System.out.println(checkDate("2007/02/31"));
    System.out.println(checkDate("aaaa/02/31"));
}

◆Output result

true
false
false
TOC