java.time
It’s time to show the modern way of doing this. Use java.time, the modern Java date and time API.
String dt = "2020-07-24T11:03:12Z";
try {
Instant i = Instant.parse(dt);
System.out.println(i);
} catch (DateTimeParseException dtpe) {
System.err.println(dtpe);
}
Output is:
2020-07-24T11:03:12Z
I am exploiting the fact that your format is ISO 8601 and the classes of java.time parse the most common variants of ISO 8601 as their default, that is, without any explicit formatter.
The exception comes into play if the string is not a valid ISO 8601 date and time in UTC. For example:
String dt = "Not a valid date-time";
java.time.format.DateTimeParseException: Text 'Not a valid date-time' could not be parsed at index 0
The classes SimpleDateFormat
and Date
are poorly designed and long outdated, the former in particular notoriously troublesome. I recommend that nobody uses them anymore. The modern API is so much nicer to work with.
Links