As Basil says, you should probably use DateTimeFormatter.ISO_INSTANT
as your format, which results in all successes and more accurate results:
Success: 2021-06-22T18:27:03.5577Z {InstantSeconds=1624386423, MilliOfSecond=557, MicroOfSecond=557700, NanoOfSecond=557700000},ISO
Success: 2021-06-22T18:27:03.55770Z {InstantSeconds=1624386423, MilliOfSecond=557, MicroOfSecond=557700, NanoOfSecond=557700000},ISO
Success: 2021-06-22T18:27:03.557700Z {InstantSeconds=1624386423, MilliOfSecond=557, MicroOfSecond=557700, NanoOfSecond=557700000},ISO
Success: 2021-06-22T18:27:03.5577000Z {InstantSeconds=1624386423, MilliOfSecond=557, MicroOfSecond=557700, NanoOfSecond=557700000},ISO
Success: 2021-06-22T18:27:03.55770000Z {InstantSeconds=1624386423, MilliOfSecond=557, MicroOfSecond=557700, NanoOfSecond=557700000},ISO
The real question though is, "What is expected of this formatter"? It seems like it's meant to be parsing instants but without documentation we're not sure. Is it really meant to fail on certain date formats which are supported by instant, is it really meant to be expecting a literal 'Z' rather than the offset? If it's intent is to be able to parse these instants accurately then changing it to actually be accurate is what you should do.
BUT If it's meant to be more restrictive and fail in weird cases then using aksappy's idea might be the way to go, since his format keeps close to your existing format but allows you to explicitly add to the pattern to match new formats you want to match.
I expect that your success with six digits after the decimal is a bug in your java.time
or whichever library is providing this API.
Running with OpenJDK 16.0.1:
public static void main(String[] args) {
DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
String[] dates = {
"2021-06-22T18:27:03.5577Z",
"2021-06-22T18:27:03.55770Z",
"2021-06-22T18:27:03.557700Z",
"2021-06-22T18:27:03.5577000Z",
"2021-06-22T18:27:03.55770000Z",
};
for (String date : dates) {
try {
System.out.println("Success: " + date + "\t\t" + TIME_FORMATTER.parse(date));
} catch (Exception e) {
System.out.println("Failure: " + date);
}
}
}
I get the following results that match what I expect based on your format:
Failure: 2021-06-22T18:27:03.5577Z Text '2021-06-22T18:27:03.5577Z' could not be parsed at index 20
Failure: 2021-06-22T18:27:03.55770Z Text '2021-06-22T18:27:03.55770Z' could not be parsed at index 20
Failure: 2021-06-22T18:27:03.557700Z Text '2021-06-22T18:27:03.557700Z' could not be parsed at index 20
Success: 2021-06-22T18:27:03.5577000Z {},ISO resolved to 2021-06-22T18:27:03.557700
Failure: 2021-06-22T18:27:03.55770000Z Text '2021-06-22T18:27:03.55770000Z' could not be parsed at index 27