Text '28Feb2020' could not be parsed, unparsed text found at index 7

302 Views Asked by At

Input Text is 20FEB2020

The following code block throws a DateTimeParseException with the message Text '28Feb2020' could not be parsed, unparsed text found at index 7:

String issueDate = abcIssueDate.substring(0, 3)
                  + abcIssueDate.substring(3).toLowerCase();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMMyy", Locale.US);
LocalDate localDate = LocalDate.parse(issueDate, formatter);
1

There are 1 best solutions below

1
On

The exception your code block throws is very likely to be caused by the pattern of your DateTimeFormatter. As already commented below your question, you are using two y for a year that has 4 digits.
So you could change the pattern to "ddMMMyyyy", which might work.

Also, I strongly recommend you to build and use a DateTimeFormatter with DateTimeFormatterBuilder#parseCaseInsensitive that parses the input string case-insensitively:

public static void main(String[] args) throws IOException {
    String time = "20FEB2020";
    // build a DateTimeFormatter that parses case-insensitively
    DateTimeFormatter dtf = new DateTimeFormatterBuilder()
                                    .parseCaseInsensitive()
                                    .appendPattern("ddMMMuuuu")
                                    .toFormatter(Locale.ENGLISH);
    LocalDate localDate = LocalDate.parse(time, dtf);
    System.out.println(localDate);
}

The result is (implicitly using the toString() method of LocalDate):

2020-02-20