[ACCEPTED]-Make SimpleDateFormat.parse() fail on invalid dates (e.g. month is greater than 12)-date

Accepted answer
Score: 142

You need to make it non-lenient. Thus,

format.setLenient(false);

should do it.

0

Score: 4

You can use the Java 8 time API. If by example 2 you use a month with a value of 15:

String strDate = "20091504";
TemporalAccessor ta = DateTimeFormatter.ofPattern("yyyyMMdd").parse(strDate);

You will 1 directly have an exception

Exception in thread "main" java.time.format.DateTimeParseException:
Text '20091504' could not be parsed:
Invalid value for MonthOfYear (valid values 1 - 12): 15
Score: 2

By using Java 8 LocalDate you can write like this,

String strDate = "20091504";
LocalDate date1 = LocalDate.parse(strDate, DateTimeFormatter.BASIC_ISO_DATE);
System.out.println(date1);

Here 1 is the Exception is thrown during parsing

Exception in thread "main" java.time.format.DateTimeParseException: Text '20091504' could not be parsed: Invalid value for MonthOfYear (valid values 1 - 12): 15
at java.time.format.DateTimeFormatter.createError(Unknown Source)
at java.time.format.DateTimeFormatter.parse(Unknown Source)
at java.time.LocalDate.parse(Unknown Source)
at com.katte.infa.DateFormatDemo.main(DateFormatDemo.java:22)

Caused by: java.time.DateTimeException: Invalid value for MonthOfYear (valid values 1 - 12): 15
at java.time.temporal.ValueRange.checkValidIntValue(Unknown Source)
at java.time.temporal.ChronoField.checkValidIntValue(Unknown Source)
at java.time.chrono.IsoChronology.resolveYMD(Unknown Source)
at java.time.chrono.IsoChronology.resolveYMD(Unknown Source)
at java.time.chrono.AbstractChronology.resolveDate(Unknown Source)
at java.time.chrono.IsoChronology.resolveDate(Unknown Source)
at java.time.chrono.IsoChronology.resolveDate(Unknown Source)
at java.time.format.Parsed.resolveDateFields(Unknown Source)
at java.time.format.Parsed.resolveFields(Unknown Source)
at java.time.format.Parsed.resolve(Unknown Source)
at java.time.format.DateTimeParseContext.toResolved(Unknown Source)
at java.time.format.DateTimeFormatter.parseResolved0(Unknown Source)
... 3 more

More Related questions