If you are using Java 8, you can use the native Java Time library that was developed by the same guy (Stephen Colebourne) who created Joda time. It's pretty easy to parse and display dates in various formats.
Your main issue seems to be that you are treating your expected object as a LocalDateTime
, but there is no time present. This is essentially throwing your code through a runtime error that states that you need to include time, so you should use a LocalDate
instead.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class StringToLocalDate {
public static String DATE_FORMAT_INPUT = "ddMMyyyy";
public static String DATE_FORMAT_OUTPUT = "yyyy-MM-dd";
public static void main(String[] args) {
System.out.println(formatted(convert("21022019")));
}
public static String formatted(LocalDate date) {
return date.format(DateTimeFormatter.ofPattern(DATE_FORMAT_OUTPUT));
}
public static LocalDate convert(String dateStr) {
return LocalDate.parse(dateStr, DateTimeFormatter.ofPattern(DATE_FORMAT_INPUT));
}
}
If you need to use a Java version before 1.8, you can use the following. It is very similar.
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
public class StringToLocalDate {
public static String DATE_FORMAT_INPUT = "ddMMyyyy";
public static String DATE_FORMAT_OUTPUT = "yyyy-MM-dd";
public static void main(String[] args) {
System.out.println(formatted(convert("21022019")));
}
public static String formatted(LocalDate date) {
return date.toString(DateTimeFormat.forPattern(DATE_FORMAT_OUTPUT));
}
public static LocalDate convert(String dateStr) {
return LocalDate.parse(dateStr, DateTimeFormat.forPattern(DATE_FORMAT_INPUT));
}
}