Search code examples
javaparsinglocaldate

Exception thrown when parsing data


Sorry if this is a rookie question, but I have the following problem: every time I try to parse a string into a LocalDate type, with a specific format (ddMMyyy) I get the following message:

Exception in thread "main" java.time.format.DateTimeParseException: Text '06071994' could not be parsed at index 2
    at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2046)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
    at java.base/java.time.LocalDate.parse(LocalDate.java:428)
    at jujj.main(jujj.java:7)

Process finished with exit code 1

At first I thought that maybe I did something wrong in a different part of the code and I tried to isolate just the part where I'm doing the parsing to test it, but no luck. This is the test code:

String in = "06071994";
DateTimeFormatter format = DateTimeFormatter.ofPattern ( "dd MM yyyy" );
LocalDate BirthDay = LocalDate.parse ( in, format );
System.out.println ( in );

Later Edit: I tried different formats: "dd/MM/yyyy" , "dd-MM-yyyy", "ddMMyyyy", they still didn't work.


Solution

  • import java.text.ParseException;
    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    
    public class FormatDate {
    
    public static void main(String... args) throws ParseException {
        String in = "06071994";
        DateTimeFormatter format = DateTimeFormatter.ofPattern("ddMMyyyy");
        LocalDate BirthDay = LocalDate.parse(in, format);
        System.out.println(BirthDay);
      }
    }
    

    Edit 1: Problem with the code was that the input was in the format ddMMyyyy(06071994) and the format was dd MM yyyy (should have been ddMMyyyy). So now parser sees that input and format to parse are not same hence it throws error.