Java - Throw error when date is invalid

1.2k views Asked by At

I have the following code:

SimpleDateFormat formatDDMMYYY = new SimpleDateFormat("dd/MM/yyyy");
Calendar quotationDay = Calendar.getInstance();
try {
    quotationDay.setTime(formatDDMMYYY.parse("06/13/2015"));
} catch (ParseException e) {
    throw new RuntimeException("Quotation date is in incorrect format.");
}

The date "06/13/2015" is incorrect, as there is no 13th month. Java automatically parses it to the next month, in 2016. Is there any way I can prevent this from happening and throw an exception?

2

There are 2 answers

0
aviad On BEST ANSWER

You need to set

formatDDMMYYY.setLenient(false);

Check the spec

0
Antonio On

You should turn off leniency as stated in docs

Leniency

Calendar has two modes for interpreting the calendar fields, lenient and non-lenient. When a Calendar is in lenient mode, it accepts a wider range of calendar field values than it produces. When a Calendar recomputes calendar field values for return by get(), all of the calendar fields are normalized. For example, a lenient GregorianCalendar interprets MONTH == JANUARY, DAY_OF_MONTH == 32 as February 1.

When a Calendar is in non-lenient mode, it throws an exception if there is any inconsistency in its calendar fields. For example, a GregorianCalendar always produces DAY_OF_MONTH values between 1 and the length of the month. A non-lenient GregorianCalendar throws an exception upon calculating its time or calendar field values if any out-of-range field value has been set.