I am trying to parse these dates in java.time and then get a String representation.
2021-12-27T09:15:09.738+02:00 2022-01-11T20:04:21+02:00
I read this similar answer and I have created a method in order to parse the above dates and return a String with the desired format:
public String getDatetimeFromDatetimeWithT(String dateFull) {
String date = "";
try {
LocalDateTime ldate = LocalDateTime.parse(dateFull, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"));
date = ldate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
} catch (Exception e) {
System.out.println(dateFull + " not matched 1 " + e);
}
try {
LocalDateTime ldate = LocalDateTime.parse(dateFull, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ"));
date = ldate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
} catch (Exception e) {
System.out.println(dateFull + " not matched 2" + e);
}
return date;
}
However, none patterns are matched. What I am missing here?
UPDATE: In both dates I get an exception for the + character.
2021-12-27T09:15:09.738+02:00 not matched 1 java.time.format.DateTimeParseException: Text '2021-12-27T09:15:09.738+02:00' could not be parsed at index 23 2022-01-11T20:04:21+02:00 not matched 2 java.time.format.DateTimeParseException: Text '2022-01-11T20:04:21+02:00' could not be parsed at index 19
Advertisement
Answer
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…