Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isLenient function to check if date is valid

Tags:

java

I am looking to check if the date I set is valid or not. This is how I have attempted to do it:

public boolean validDate() {
    return calendar.isLenient();
}

Calling it like this:

Date date = new Date(36, 04, 2014);
System.out.println("Day = " + date.getDay());
System.out.println("Month = " + date.getMonth());
System.out.println("Year = " + date.getYear());
System.out.println("Is valid? = " + date.validDate());
System.out.println("Last day? = " + date.LastDayOfMonth(02));

And it returns this -

Day = 36
Month = 4
Year = 2014
Is valid? = true
Last day? = false

My question is why does it say it is valid even though it is not. Also how would I check to see if it is a false date or not?

like image 547
user3456349 Avatar asked Nov 18 '25 16:11

user3456349


1 Answers

A Calendar can be either in "lenient" or "non-lenient" mode. If it's in lenient mode, it can accept invalid values (like day=36) and interpret them somehow; if it's in non-lenient mode and you try to set invalid values, an exception will be thrown (but not necessarily right away; see this question.

isLenient will tell you whether the Calendar is in lenient or non-lenient mode, but it tells you nothing about whether the data is valid.

To test whether the values are valid, you can try another Calendar in non-lenient mode. Your class has day, month, and year fields, so you can try something like:

public boolean validDate() {
    try {
        Calendar tempCal = Calendar.getInstance();
        tempCal.setLenient(false);
        tempCal.set(Calendar.MONTH, month);
        tempCal.set(Calendar.YEAR, year);
        tempCal.set(Calendar.DAY_OF_MONTH, day);
        tempCal.get(Calendar.MONTH);
            // throws ArrayIndexOutOfBoundsException if any field is invalid; we don't care about the
            // method result
        return true;
    } catch (ArrayIndexOutOfBoundsException | IllegalArgumentException e) {
        return false;
    }
}

Note that this doesn't affect your calendar field which may still be in lenient mode.

EDIT: Now tested. The javadoc says get() throws ArrayIndexOutOfBoundsException if any data is invalid, but I believe this may be an error in the javadoc. I'll try to report this to Oracle.

like image 151
ajb Avatar answered Nov 21 '25 05:11

ajb