javadatetime-formatjava-timelocaldatedatetime-parsing

Formatting date in java.time


I am trying to format date were is given in following format 05051988. I want to use LocalDate to format in next 05 may 1988.

I have create private method that i will use later in same class to input formatted date in text. I have already made some code but i at the moment I'm getting 1988-05-05 if I use MM, if I replace it with MMM then it is giving me error message that can not be parsed.

private LocalDate parseDate(){
    LocalDate dateOfBirth = LocalDate.parse(date, DateTimeFormatter.ofPattern("ddMMyyyy"));
    return dateOfBirth;
}

Error:

Exception in thread "main" java.time.format.DateTimeParseException: Text '05051988' could not be parsed at index 2

Solution

  • You still need to use "ddMMyyyy" to parse the date. Then use "dd MMM yyyy" to format it when you print it.

    Something like this:

    String reformat(String dateOfBirth) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyy");
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("dd MMM yyyy");
        LocalDate date = LocalDate.parse(dateOfBirth, fomatter);
        return formatter2.print(date);
    }