Parse String datetime with Zone with Java Date
You don't even need to define a pattern, your examples are ISO formatted and they contain an offset rather than a zone.
That's why you can use this alternative (if you want to stick to LocalDateTime
):
// parse without passing a formatter
OffsetDateTime odtA = OffsetDateTime.parse("2021-12-27T09:15:09.738+02:00");
OffsetDateTime odtB = OffsetDateTime.parse("2022-01-11T20:04:21+02:00");
// extract the LocalDateTimes
LocalDateTime ldtA = odtA.toLocalDateTime();
LocalDateTime ldtB = odtB.toLocalDateTime();
// print them
System.out.println(ldtA);
System.out.println(ldtB);
Result:
2021-12-27T09:15:09.738
2022-01-11T20:04:21
To make your method shorter, write something like this:
public static String getDatetimeFromDatetimeWithT(String dateFull) throws DateTimeParseException {
return OffsetDateTime.parse(dateFull)
.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
}
This basically parses the String
argument to an OffsetDateTime
and formats that OffsetDateTime
using only the information a LocalDateTime
has.
Result stays the same as posted above…
Your date pattern is not correct. Use this:
yyyy-MM-dd'T'HH:mm:ss.SSSXXX
Or use one of the predefined ISO standard classes to do the parsing for you:
DateTimeFormatter.ISO_ZONED_DATE_TIME.parse(dateFull);