Home > other >  LocalDate.parse can't parse the character on the last index wehere there is no character (nor e
LocalDate.parse can't parse the character on the last index wehere there is no character (nor e

Time:12-20

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]?

CodePudding user response:

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);
  • Related