java.time
The accepted answer uses legacy date-time API which was the correct thing to do using the standard library in 2011 when the question was asked. In March 2014, java.time
API supplanted the error-prone legacy date-time API. Since then, it has been strongly recommended to use this modern date-time API.
The java.time API is based on ISO 8601 and for basic format i.e. yyyyMMdd, it comes with a predefined formatter, DateTimeFormatter.BASIC_ISO_DATE
.
Using this predefined formattter, try to parse your string to a LocalDate
and catch
the exception, if any, to understand the cause.
Demo using java.time API:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class Main {
public static void main(String[] args) {
String[] samples = { "20221123", "20110133", "20110131", "20110229", "20110228" };
for (String dateString : samples) {
try {
System.out.println("============================");
System.out.println(
dateString + " parsed to " + LocalDate.parse(dateString, DateTimeFormatter.BASIC_ISO_DATE));
} catch (DateTimeParseException e) {
System.err.println(e.getMessage());
}
}
}
}
Output:
============================
20221123 parsed to 2022-11-23
============================
Text '20110133' could not be parsed: Invalid value for DayOfMonth (valid values 1 - 28/31): 33
============================
20110131 parsed to 2011-01-31
============================
Text '20110229' could not be parsed: Invalid date 'February 29' as '2011' is not a leap year
============================
20110228 parsed to 2011-02-28
Learn more about the modern Date-Time API from Trail: Date Time.