0

Hi I am not able to understand what time format we need to use in order to parse this date2020-02-11T17:26:31-05:00 I have tried using Date formatter and simple date format but its not working

Date is coming in this form ->2020-02-11T17:26:31-05:00 I am not able to identify the type of this date

Below is snippet of code i have tried but its throwing exception

DateTimeFormatter responseFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss-SSSXXX'Z'",
                              Locale.ENGLISH);
                     responseDateTime = LocalDateTime.parse(otmmResponseDate, responseFormatter);
ankur jadiya
  • 129
  • 2
  • 3
  • 13
  • 1
    Does this answer your question? [Converting ISO 8601-compliant String to java.util.Date](https://stackoverflow.com/questions/2201925/converting-iso-8601-compliant-string-to-java-util-date) Or https://stackoverflow.com/a/4216767/2131074 – GPI Feb 19 '20 at 12:36
  • This is a ISO 8601 compliant instant format. You should check out other answers with this keyword. Look for java.time based solutions Java versions after 8. – GPI Feb 19 '20 at 12:37

2 Answers2

4

Notice that your date string has an offset -05:00 in it. Thus, your string does not represent a LocalDateTime, but an OffsetDateTime, and should be parsed by OffsetDateTime.parse (not everything is a LocalDateTime!):

// the format is ISO 8601, so it can be parsed directly without a DateTimeFormatter
OffsetDateTime odt = OffsetDateTime.parse("2020-02-11T17:26:31-05:00");

If you only want the local date time part of it, then you can call toLocalDateTime afterwards:

LocalDateTime ldt = odt.toLocalDateTime();
Sweeper
  • 213,210
  • 22
  • 193
  • 313
1

This is a datetime String that contains an offset of minus five hours. You don't even have to use a DateTimeFormatter directly, because parsing this to an OffsetDateTime will do:

public static void main(String[] args) {
    String dateString = "2020-02-11T17:26:31-05:00";
    OffsetDateTime odt = OffsetDateTime.parse(dateString);

    System.out.println(odt.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
}

Output:

2020-02-11T17:26:31

Not that this uses a DateTimeFormatter without an offset for the output.

deHaar
  • 17,687
  • 10
  • 38
  • 51