0

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.

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.

Fabien Warniez
  • 2,731
  • 1
  • 21
  • 30

2 Answers2

1

Follow the documentation of 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

2017-08-09T17:11:53Z

It seems from the Twitter documentation that offset will always be +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. If you want stricter validation, you may also check that the OffsetDateTime’s .getOffset().equals(ZoneOffset.UTC) yields true before you convert to Instant.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
-2

Found the solution

Instant.from(DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(dateStr))
Fabien Warniez
  • 2,731
  • 1
  • 21
  • 30
  • 1
    Are you sure this parses the string `Wed Aug 09 17:11:53 +0000 2017`? –  Oct 19 '17 at 00:28
  • 1
    I get `java.time.format.DateTimeParseException: Text 'Wed Aug 09 17:11:53 +0000 2017' could not be parsed at index 0`. – Ole V.V. Oct 19 '17 at 09:44