Here is my method to parse String into LocalDateTime
.
public static String formatDate(final String date) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SS");
LocalDateTime formatDateTime = LocalDateTime.parse(date, formatter);
return formatDateTime.atZone(ZoneId.of("UTC")).toOffsetDateTime().toString();
}
but this only works for input String like
2017-11-21 18:11:14.05
but fails for 2017-11-21 18:11:14.057
with DateTimeParseException
.
How can I define a formatter that works for both .SS
and .SSS
?
return formatDateTime.atOffset(ZoneOffset.UTC).toString();
. – Coquito