简体   繁体   中英

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.

Clearly, your pattern does not match your string.

Your string contains no spaces while your pattern does.

Your string contains a two digit month while your pattern is expecting a three letter abbreviation of the month name.

Try the following code:

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

All the valid patterns are detailed and explained in the javadoc of class DateTimeFormatter

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM