SimpleDateFormat
doesn't know the supported range of year where the date will be stored, so you need to validation the date.
Since you mentioned MySQL, and the DATETIME
data type supports years in range 1000-9999, you should do this:
static Date parseDate(String dateStr) throws ParseException {
// Parse the string (strict)
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
fmt.setLenient(false); // Reject invalid month and day values
Date date = fmt.parse(dateStr);
// Validate year
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
if (year < 1000 || year > 9999)
throw new IllegalArgumentException("Invalid year: \"" + dateStr + "\"");
return date;
}
The important parts are:
Turn on strict parsing mode, to ensure month
and day
values are in valid ranges.
Custom check to ensure year
value is in valid range.
It might be better if you could use the newer Java 8+ Time API, in which case the code would be:
static LocalDate parseDate(String dateStr) {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("uuuu-MM-dd")
.withResolverStyle(ResolverStyle.STRICT);
LocalDate date = LocalDate.parse(dateStr, fmt);
if (date.getYear() < 1000 || date.getYear() > 9999)
throw new DateTimeException("Invalid value for Year (valid values 1000 - 9999): " + date.getYear());
return date;
}
Same as before: Strict parsing and custom year range check.