Skip to content
Advertisement

LocalDate.parse can’t parse the character on the last index wehere there is no character (nor empty space)

I have in my notepad file text:

19-12-2021

I checked is there any empty spaces, there is none.

When I write:

String noticeLastUpdateDate = textFileDAO.getMoneyTableNoticeLastUpdateDate();
DateTimeFormatter formatterDate = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate dateNow = LocalDate.parse(noticeLastUpdateDate, formatterDate);

I receive an error:

java.time.format.DateTimeParseException: Text '19-12-2021
' could not be parsed, unparsed text found at index 10

But there is no index 10! Why it thinks there is index[10]?

Advertisement

Answer

Trim possible whitespaces before parsing the date using String::trim:

String trimmedDate = textFileDAO.getMoneyTableNoticeLastUpdateDate().trim();
DateTimeFormatter formatterDate = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate dateNow = LocalDate.parse(trimmedDate, formatterDate);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement