1

I try to format a Datestring to OffsetDateTime with the Java buildIn DateTimeFormatter. My DateTimeFormatter does not work as expected.

The String is: "2018-11-12T14:55:17 +0100"

DateTimeFormatter.ofPattern("yyyy-MM-dd'T'hh:mm:ssZ");
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'hh:mm:ssZZZZZ");
DateTimeFormatter.ISO_OFFSET_DATE_TIME;

I expected, that with the DateTimeFormater I will get a proper OffsetDateTime. may one can help me out of this situation?

E.Lmo
  • 71
  • 1
  • 8
  • Related, and possibly a duplicate of: (1) [Java: Date parsing, why do I get an error](https://stackoverflow.com/questions/48666263/java-date-parsing-why-do-i-get-an-error) (2) [Not able to convert the string to date on Android](https://stackoverflow.com/questions/50988150/not-able-to-convert-the-string-to-date-on-android) – Ole V.V. Aug 04 '19 at 07:21
  • And for the case of `hh` partly a duplicate of [DateTimeParseException: Text '2019-06-07 12:18:16' could not be parsed](https://stackoverflow.com/questions/56500476/datetimeparseexception-text-2019-06-07-121816-could-not-be-parsed) or [Convert string into LocalDateTime](https://stackoverflow.com/questions/57096793/convert-string-into-localdatetime) – Ole V.V. Aug 04 '19 at 07:30
  • It’s unclear whether you were trying to *parse* (convert string to `OffsetDateTime`) or *format* (the opposite conversion)? – Ole V.V. Aug 04 '19 at 07:34

2 Answers2

1

No need of any formatter you can directly parse the string into OffsetDateTime, remove the space and add colon between minutes and seconds

OffsetDateTime time = OffsetDateTime.parse("2018-11-12T14:55:17+01:00");
System.out.println(time);

A date-time with an offset from UTC/Greenwich in the ISO-8601 calendar system, such as 2007-12-03T10:15:30+01:00.

Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
1

I found the solution:

DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss X");

Big HH and the X facepalm

E.Lmo
  • 71
  • 1
  • 8
  • Thanks for answering your own question (you may also accept your own answer). I get `2019-08-04T09:24:36 +02`. Two points: (1) According to ISO 8601 there should not be a space between `ss` and `X`. (2) For four digit offset, hours and minutes, as in `+0200`, use two `X`s. So `yyyy-MM-dd'T'HH:mm:ssXX`. – Ole V.V. Aug 04 '19 at 07:27