I recommend you to do it using the modern date-time API*
Use DateTimeFormatter#withResolverStyle(ResolverStyle.STRICT)
to resolve a date strictly.
import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.ResolverStyle;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDate = "2021/02/31";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu/MM/dd", Locale.ENGLISH)
.withResolverStyle(ResolverStyle.STRICT);
try {
LocalDate date = LocalDate.parse(strDate, dtf);
// ...
} catch (DateTimeException e) {
System.out.println(e.getMessage());
}
}
}
Output:
Text '2021/02/31' could not be parsed: Invalid date 'FEBRUARY 31'
Learn more about the modern date-time API from Trail: Date Time.
Also, note that yyyy-mm-dd
is not a correct format for your date string which has /
instead of -
and m
is used for a minute, not a month for which you have to use M
.
The java.util
date-time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API. For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.