简体   繁体   English

如何将 Twitter API 日期解析为 java.time.Instant?

[英]How can I parse Twitter API dates into java.time.Instant?

I am trying to parse the dates that come from the Twitter API into the new Instant class from Java 8. FYI, this is the format Wed Aug 09 17:11:53 +0000 2017 .我正在尝试将来自 Twitter API 的日期解析为来自 Java 8 的新Instant类。仅供参考,这是Wed Aug 09 17:11:53 +0000 2017的格式。

I don't want to deal with / set a time zone, as one is specified in the string already.我不想处理/设置时区,因为已经在字符串中指定了一个时区。 I just want an Instant instance.我只想要一个Instant实例。

Follow the documentation of DateTimeFormatter :按照DateTimeFormatter文档

    DateTimeFormatter dtf 
            = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss X uuuu", Locale.ROOT);
    Instant asInstant = OffsetDateTime.parse(dateStr, dtf).toInstant();

With your example string the result is an Instant of使用您的示例字符串,结果是Instant

2017-08-09T17:11:53Z

It seems from the Twitter documentation that offset will always be +0000 .Twitter 文档看来, offset 将始终为+0000 Depending on how strongly you trust this to be the case, you may use small x or capital Z instead of capital X in the format pattern.根据您对这种情况的信任程度,您可以在格式模式中使用小写x或大写Z而不是大写X If you want stricter validation, you may also check that the OffsetDateTime 's .getOffset().equals(ZoneOffset.UTC) yields true before you convert to Instant .如果您想要更严格的验证,您还可以在转换为Instant之前检查OffsetDateTime.getOffset().equals(ZoneOffset.UTC)是否为 true 。

找到解决方案

Instant.from(DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(dateStr))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM