Parse ISO timestamp using Java 8 java.time api (standard edition only)

Travis Wellman picture Travis Wellman · Sep 9, 2014 · Viewed 15k times · Source

I'm having trouble getting milliseconds from the epoch out of the string in the example. I have tried this three different ways so far, and the example shows the latest attempt. It always seems to come down to that the TemporalAccessor does not support ChronoField. If I could successfully construct an instance of Instant, I could use toEpochMilli().

String dateStr = "2014-08-16T05:03:45-05:00"
TemporalAccessor creationAccessor = DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(dateStr);
Instant creationDate = Instant.from(creationAccessor);

Please give concise answers (don't construct a formatter from scratch) and use only the java 8 standard distribution (I can do it with Joda, but want to avoid dependencies).

Edit: Instant.from in the code above throws: java.time.DateTimeException: Unable to obtain Instant from TemporalAccessor: {OffsetSeconds=-18000},ISO resolved to 2014-08-16T05:03:45 of type java.time.format.Parsed

Answer

Holger picture Holger · Sep 9, 2014

This seems to be a bug which I found in all tested versions before and including jdk1.8.0_20b19 but not in the final jdk1.8.0_20. So downloading an up-to-date jdk version would solve the problem. It’s also solved in the most recent jdk1.9.

Note that the good old Java 7 way works in all versions:

long epochMillis = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX")
                  .parse(dateStr).getTime();

It also supports getting an Instant:

Instant i=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX").parse(dateStr).toInstant();
long epochMillis = i.toEpochMilli();

But, as said, a simple update makes your Java 8 code working.