如何在 Java 中修复 'Date Time Parse Exception'

How to fix 'Date Time Parse Exception' in Java

我有一个日期时间格式化程序,我正在尝试将输入的日期格式化为如下所示的格式 (d/MM/yyyy)

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

然后我使用此格式化程序将用户输入的出生日期作为字符串,然后尝试对其进行解析以存储为 LocalDate 变量,临时存储用户输入的出生日期

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);
    }

然而,这总是 returns DateTimeParseException:文本无法解析。我如何设置日期时间格式化程序总是导致此异常的问题吗?如下所示

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)

我想你忘记了参数,这里是修复:

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);
}

传递你的DateTimeFormatter对象。

改变这个:

LocalDate date = LocalDate.parse(temp);

…对此:

LocalDate date = LocalDate.parse(temp, format);