androidjava-8java-timeandroid-dateandroid-dateutils

DateTimeFormatter class exeception DateTimeParseException


I want to get next 3 months date from the enter date in android device. for versions greater than oreo I tried to use DateTimeFormatter. but I got this error "java.time.format.DateTimeParseException: Text '28/5/2020' could not be parsed at index 0"

This is my enter date string = 28/5/2020

   String datestring = edittext_enterServiceDate.getText().toString();
                String dd = datestring.substring(0, 2);
                String mm = datestring.substring(3, 4);
                String yyyy = datestring.substring(5, 9);
                String dateString = dd + "/" + mm + "/" + yyyy;
                LocalDate date = LocalDate.parse(dd + "/" + mm + "/" + yyyy);

                DateTimeFormatter df = DateTimeFormatter.ofPattern("dd/MM/yyyy");
                LocalDate  d1 = LocalDate.parse(dateString, df);

                LocalDate returnvalue
                        = d1.plusMonths(Integer.parseInt(monthList.get(position).getStateId()));
                edittext_nextServiceDate.setText(String.valueOf(returnvalue.toString()));

Solution

  • In doc:

    Number: If the count of letters is one, then the value is output using the minimum number of digits and without padding.

    Use format dd/M/yyyy for your date string. It will parse date Strings like 28/5/2020 and 28/12/2020 both.

    DateTimeFormatter df = DateTimeFormatter.ofPattern("dd/M/yyyy");
    LocalDate  d1 = LocalDate.parse("28/5/2020", df);
    LocalDate  d2 = LocalDate.parse("28/07/2020", df);
    LocalDate  d3 = LocalDate.parse("28/12/2020", df);