Convert String to LocalDate

Tags: , , ,



I want to convert 21022019 to 2019-02-21, but some reason I am not able to convert.

import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.joda.time.format.DateTimeFormat;

public class StringToLocalDate {
    public static void main(String[] args) {
        System.out.println(convert("21022019"));
    }

    static LocalDate convert(String date) {
        LocalDateTime ldt;
        ldt = LocalDateTime.parse(date, DateTimeFormat.forPattern("YYYY-MM-dd"));
        return LocalDateTime.now().toLocalDate();
    }
} 

Answer

You should use another pattern to parse input date

   public static void main(String[] args) {

        System.out.println(convert("21022019"));
    }

    static LocalDate convert(String date) {
        return LocalDate.parse(date, DateTimeFormat.forPattern("ddMMyyyy"));
    }


Source: stackoverflow