I don't know why there is no error. The code is
String datestr = "2021-01-01";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
try {
System.out.println(sdf.parse(datestr));
} catch (ParseException e) {
e.printStackTrace();
}
Since the date string, 2021-01-01
, does not match the format pattern string, yyyy-MM
, I had expected and wanted an exception.
The console prints Fri Jan 01 00:00:00 CST 2021
.
The opposite situation does result in an exception as expected. I make code look like this
String datestr = "2021-01";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
System.out.println(sdf.parse(datestr));
} catch (ParseException e) {
e.printStackTrace();
}
The console prints an error msg: Unparseable date: "2021-01"
Who can tell me why?
Others have already mentioned why this happens (the java parsers stop parsing when they get all they need) and have also explained that this API is older and not as ergonomic. That said, you can do what you want using the
ParsePosition
class.