IsLenient to check if a date is valid

I want to check if the date I have set is valid or not. This is how I tried to do it:

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

      

Call 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 it says it is valid even if it isn't. Also how can I check if this is a false date or not?

+3


source to share


1 answer


A Calendar

can be either "soft" or "non-lenient". If it is in softening mode, it can take invalid values โ€‹โ€‹(for example, day = 36) and interpret them somehow; if it's in non-leniency mode and you try to set invalid values, an exception will be thrown (but not necessarily immediately, see this question .

isLenient

will tell you if it's Calendar

in soft or non-lenient mode, but it doesn't tell you anything about the validity of the data.

To check if the values โ€‹โ€‹are valid, you can try another one Calendar

in non-preferential mode. Your class has fields day

, month

and year

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 does not affect your pitch Calendar

, which may still be in lowered mode.

EDIT: Tested now. The Javadoc says get()

throws ArrayIndexOutOfBoundsException

if any data is invalid, but I believe it might be a bug in the javadoc. I'll try to communicate this to Oracle.

0


source







All Articles