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?
2021-01withyyyy-MM-dd, while parsing2021-01-01withyyyy-MM??? I'm really curious...SimpleDateFormatandDate. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead useLocalDateandYearMonth, both from java.time, the modern Java date and time API.SimpleDateFormatis not a function, it is a class. While in this case it was clear what you meant, in other cases using the right and agreed-upon terms will make the difference between people knowing exactly what you mean and people either not having a clue or worse, completely misunderstanding your intentions.