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?
You are describing two different scenarios:
#1 is not an error, since
parse(String)is explicitly documented to just read from the beginning of the input until it has enough:#2 is an error, because you the pattern says it expects extra data (namely a
-followed by a day) and that data is missing.