I agree with the comments by Joe C and Louis Wassermann: stay off the long outdated Date class if there’s any way you can. And there is. The modern replacement classes are so much more convenient and programmer friendly.
Furthermore, your input string conforms to the ISO 8601 standard for an instant, a point in time, so fits the Instant class precisely. No need for any explicit formatter for parsing it. I suggest:
private static Instant parse(String inputString) {
try {
return Instant.parse(inputString);
} catch (DateTimeParseException dtpe) {
System.err.println("Parsing: " + dtpe);
return Instant.now();
}
}
Use the method like the following, for example:
String inputString = "2017-06-01T01:00:00Z";
System.out.println(parse(inputString));
This prints:
2017-06-01T01:00:00Z
Well, it’s the same string you started out from, because Instant.toString() produces the same ISO 8601 string back.
I admit scottb a point too: we sometimes need to interoperate with legacy code that does require an oldfashioned Date instance. If this is your case, produce one from Date.from(parse(inputString)). This will produce a Date equal to the instant (on my computer printed as Thu Jun 01 03:00:00 CEST 2017 because that happens to be my time zone). In any case I recommend converting to Date in the last moment before entering your legacy code to minimize your own use of it.
Just for the experiment, let’s try to use your incorrect format pattern string with the newer DateTimeFormatter class:
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ").parse(inputString);
This yields a java.time.format.DateTimeParseException: Text '2017-06-01T01:00:00Z' could not be parsed at index 19. It’s trying to be helpful to you: index 19 of 2017-06-01T01:00:00Z is where it says Z. As the two other answers say, this is exactly where the format pattern doesn’t match the input. Take my word, this is just one example out of many where you get better help from the modern classes than from the old ones.
java.util.Dateclass. You should instead use the appropriate class in thejava.timepackage.java.util.Datedeprecated. The whole thing.Date. DogmaticDatehate is not appropriate. UseDateif the solution to your problem calls for it, but do be aware of its weaknesses.