Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 902
Travis Wellman Avatar asked Sep 09 '14 01:09

Travis Wellman


People also ask

What is an instant in the Java 8 Date and time API?

The Java Date Time API was added from Java version 8. instant() method of Clock class returns a current instant of Clock object as Instant Class Object. Instant generates a timestamp to represent machine time. So this method generates a timestamp for clock object.

What can I use instead of SimpleDateFormat?

DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.

Is Java time format DateTimeFormatter thread-safe?

Yes, it is: DateTimeFormat is thread-safe and immutable, and the formatters it returns are as well. Implementation Requirements: This class is immutable and thread-safe.


1 Answers

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.

like image 173
Holger Avatar answered Oct 09 '22 08:10

Holger