2

I have a Date Time Formatter Which I am trying to format inputted dates into format (d/MM/yyyy) Shown Below

DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy");

I am then using this formatter to take user input on date of birth as a String and then attempting to parse that through to store as a LocalDate variable with temp storing the user inputted date of birth

public void addCustomer() throws ParseException {
        customerID++;
        //Create Scanner
        Scanner scan = new Scanner(System.in);

        //Take user input
        System.out.println("Please enter your name: ");
        String name = scan.nextLine();
        System.out.println("Please enter your Date of Birth(dd/MM/yyyy): ");
        String temp = scan.nextLine();
        LocalDate date = LocalDate.parse(temp);
        Customer c = new Customer(customerID, name, date, false, "N/A");
        customers.add(c);
    }

However this always returns a DateTimeParseException: Text could not parse. Is the issue in how I am setting up the Date Time Formatter to always cause this exception? Shown Below

Exception in thread "main" java.time.format.DateTimeParseException: Text '27/01/1999' could not be parsed at index 0
    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 java.base/java.time.LocalDate.parse(LocalDate.java:413)
    at BikeNow.addCustomer(BikeNow.java:153)
    at BikeNow.main(BikeNow.java:98)
Chornologic
  • 117
  • 2
  • 8

2 Answers2

4

Pass your DateTimeFormatter object.

Change this:

LocalDate date = LocalDate.parse(temp);

…to this:

LocalDate date = LocalDate.parse(temp, format);
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Rmahajan
  • 1,311
  • 1
  • 14
  • 23
2

I think that you forgot the parameter, here is the fix:

public void addCustomer() throws ParseException {
        customerID++;
        //Create Scanner
        Scanner scan = new Scanner(System.in);

        //Take user input
        System.out.println("Please enter your name: ");
        String name = scan.nextLine();
        System.out.println("Please enter your Date of Birth(dd/MM/yyyy): ");
        String temp = scan.nextLine();

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
        LocalDate date = LocalDate.parse(temp, formatter);
        Customer c = new Customer(customerID, name, date, false, "N/A");
        customers.add(c);
}
Vinh Can Code
  • 407
  • 3
  • 14