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
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.
DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With