I just wrote this unit tests :
@Test
public void testGetDateFromString() throws ParseException{
String date = "52/29/2500";
Date dateFromString = DateHelper.getDateFromString(date, DateHelper.DD_MM_YYYY_FORMAT);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DateHelper.DD_MM_YYYY_FORMAT);
Date dateWithSimpleFormat = simpleDateFormat.parse(date);
Assert.assertNotNull(dateFromString);
Assert.assertNotNull(dateWithSimpleFormat);
Assert.assertTrue(dateFromString.equals(dateWithSimpleFormat));
System.out.println("dateFromString " + dateFromString);
System.out.println("dateWithSimpleFormat " + dateWithSimpleFormat);
}
And the output is :
dateFromString Wed Jun 21 00:00:00 CEST 2502
dateWithSimpleFormat Wed Jun 21 00:00:00 CEST 2502
The DateHelper.DD_MM_YYYY_FORMAT pattern is dd/MM/yyyy and getDateFromString is a method that parses a String date to a Date object using commons-lang library.
Why des the java.util.Date object verifies the date validity?
解决方案
You need to set simpleDateFormat.setLenient(false); to make the SimpleDateFormat to validate your input strictly.
You can refer the setLenient documentation for further understanding. By the definition,
Specify whether or not date/time parsing is to be lenient. With lenient parsing,
the parser may use heuristics to interpret inputs that do not precisely match this
object's format. With strict parsing, inputs must match this object's format.