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)
答案 0 :(得分:4)
Pass your DateTimeFormatter
object.
Change this:
LocalDate date = LocalDate.parse(temp);
…to this:
LocalDate date = LocalDate.parse(temp, format);
答案 1 :(得分: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);
}