You should consider using the DateTimeFormatter and ZonedDateTime for this example. Date
and SimpleDateFormat
are old classes, and have been prone to errors and can be problematic; the newer classes mentioned (Java8+) are much more robust.
And change the end of your pattern from ...mm:ss.sssZ
to ...mm:ss.SSSz
.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSz");
ZonedDateTime zonedDateTime = ZonedDateTime.parse(date, formatter);
System.out.println(formatter.format(zonedDateTime));
You could also use OffsetDateTime or Instant (credit: Ole V.V) which will parse for you, giving the same output:
System.out.println(OffsetDateTime.parse("2018-07-17T09:59:51.312Z"));
System.out.println(Instant.parse("2018-07-17T09:59:51.312Z"));
Output:
2018-07-17T09:59:51.312Z