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

标签 java datetime-format localdate parseexception

我有一个日期时间格式化程序,我正在尝试将输入的日期格式化为如下所示的格式 (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);
    }

然而,这总是返回 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)

最佳答案

传递您的 DateTimeFormatter 对象。

改变这个:

LocalDate date = LocalDate.parse(temp);

……对此:

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

关于java - 如何在 Java 中修复 'Date Time Parse Exception',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55574157/

相关文章:

java - Android:简单线程示例崩溃

java - LocalDate Formatter 月份基数

python - `to_datetime` 限制或误用?值错误: Doesn't match format specified

Java 8 LocalDateTime - 如何获取两个日期之间的所有时间

java - 在 Android 中获取两个选定日期之间的正确差异(以年、月和日为单位)

java - Android 广播 - 发送和接收权限

java - 同一属性上的 @JsonIgnore 和 @JsonProperty

java - 为什么我不能像获取行那样简单地获取一维列数组?

javascript - 将 JavaScript 日期格式化为 yyyy-mm-dd

java - 使用 Sqlite 查询,从存储的毫秒中获取日期