Skip to content
Advertisement

Convert String to LocalDate

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();
    }
} 

Advertisement

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"));
    }
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement