java.time
It is time for the modern answer: always use java.time, the modern Java date and time API, for your date and time work. When this question was asked, java.time had been out with Java 8 for 7 months. Today (2020) no one should use the SimpleDateFormat
class that appears to have been the trouble in the question. It is notoriously troublesome and long outdated.
Using java.time we need no explicit formatter:
String str = "2014-09-17T12:00:44.0000000Z";
Instant i = Instant.parse(str);
System.out.println("As Instant: " + i);
Output is:
As Instant: 2014-09-17T12:00:44Z
Your format is ISO 8601 (link at the bottom). The classes of java.time generally parse ISO 8601 as their default and print ISO 8601 back from their toString
methods. In ISO 8601 the fraction of second is optional.
If you need a Date
object for a legacy API not yet upgraded to java.time:
Date oldfashionedDate = Date.from(i);
System.out.println("As old-fashioned Date: " + oldfashionedDate);
Output in my time zone:
As old-fashioned Date: Wed Sep 17 14:00:44 CEST 2014
Output will vary by time zone because Date.toString()
confusingly takes the JVM’s default time zone and uses it for rendering the string.
What went wrong for you?
You haven’t shown us your code, but we can already tell that a couple of things are wrong:
SimpleDateFormat
cannot parse a string with 7 fractional digits on the seconds correctly. It supports only milliseconds, exactly three decimals.
- In your format pattern string you need to escape the literal
T
by enclosing it in single quotes, 'T'
, or SimpleDateFormat
will understand it as a pattern letter, and there is no format pattern letter T
. This is what your exception message meant.
Links