使用Java解析ISO时间戳记8 java.time api(仅限标准版) [英] Parse ISO timestamp using Java 8 java.time api (standard edition only)
问题描述
我在本例中的字符串中从时代获取毫秒的时间有困难。到目前为止,我已经尝试了这三种不同的方式,这个例子显示了最新的尝试。它总是似乎归结为: TemporalAccessor 不支援 ChronoField 。如果我可以成功构建一个Instant的实例,我可以使用 toEpochMilli()。
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);
请提供简洁的答案(不要从头开始构建格式化程序),并仅使用java 8标准分发(我可以用Joda做,但是要避免依赖)。
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).
编辑: Instant.from在上面的代码中throws: code> java.time.DateTimeException:无法从TemporalAccessor获取Instant:{OffsetSeconds = -18000},ISO解析为2014-08-16T05:03:45,类型为java.time.format.Parsed
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
推荐答案
这似乎是一个在所有测试版本之前发现的错误,包括 jdk1.8.0_20b19
,但不在最终的 jdk1.8.0_20
中。因此,下载最新的jdk版本会解决问题。在最新的jdk1.9中也解决了这个问题。
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.
请注意,所有版本的旧Java 7方式都可以使用:
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();
它还支持获取 Instant
:
Instant i=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX").parse(dateStr).toInstant();
long epochMillis = i.toEpochMilli();
但是,如上所述,一个简单的更新使您的Java 8代码工作。
But, as said, a simple update makes your Java 8 code working.
这篇关于使用Java解析ISO时间戳记8 java.time api(仅限标准版)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!