0

I have a scanner to take 2 String and change them into LocalDate but it doesn't take the scanners in count and gave me this error

Exception in thread "main" java.time.format.DateTimeParseException: Text '' could not be parsed at index 0
at java.time.format.DateTimeFormatter.parseResolved0(Unknown Source)
at java.time.format.DateTimeFormatter.parse(Unknown Source)
at java.time.LocalDate.parse(Unknown Source)     .....................location of my classes

The code :`

String date1 = sc1.nextLine();
String date2 = sc1.nextLine();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
    LocalDate dateDebut = LocalDate.parse(date1,formatter);

    System.out.println(dateDebut);
    a1.setDateDeb(dateDebut);

    System.out.println(dateFin);
    a1.setDateFin(dateFin);

But when instead of the 2 scanners I put a String date ("12/12/2019") it works.

I don't know where it comes from.. I'm using Eclipse

1 Answers1

1

This error will occure while you enter the date in different format. You need to key in the date with dd/mm/yyyy format.

    Scanner sc1 = new Scanner (System.in);
    System.out.println("Enter Date1:");
    String date1 = sc1.nextLine();
    System.out.println("Enter Date2:");
    String date2 = sc1.nextLine();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
        LocalDate dateDebut = LocalDate.parse(date1,formatter);

        System.out.println(dateDebut);
      //  a1.setDateDeb(dateDebut);
        LocalDate dateFin = LocalDate.parse(date2,formatter);

        System.out.println(dateFin);
      //  a1.setDateFin(dateFin);

When we run the above code it will prompt to enter 2 dates.

Output: Enter Date1: 05/05/2025 Enter Date2: 01/10/2022

2025-05-05 2022-10-01

Sekhar
  • 51
  • 3