Error: Text ‘1/31/2020’ could not be parsed at index 0 while trying to parse string date

Tags: , , ,



I have a date as string as below

String test Date = "1/31/2020";

I am using the below code

public static String getPeriodMonth(String periodEndDate) {
        LocalDate localDate;
        YearMonth yearMonth = null;
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
            localDate = LocalDate.parse(periodEndDate, formatter);
            yearMonth = YearMonth.from(localDate);
        }catch (Exception e) {
             LOGGER.error("Error: "+ e.getMessage() + ">>" +   e.getCause());
        }
        return yearMonth.toString();

    }

I am getting the below Exception when excuting this code:

Error: Text '1/31/2020' could not be parsed at index 0>>null

Can someone help me what I am doing wrong here?

Answer

You should pass 01/31/2020or update the format to M/dd/yyyy

DateTimeFormatter documentation

The month is considered as a number and in the documentation :

Number: If the count of letters is one, then the value is output using the minimum number of digits and without padding. Otherwise, the count of digits is used as the width of the output field, with the value zero-padded as necessary.



Source: stackoverflow