skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    Found the solution

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

  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search