java.time.format.DateTimeParseException:无法在索引 2 处解析文本“13/11/2020”

java.time.format.DateTimeParseException: Text '13/11/2020' could not be parsed at index 2

我在从字符串转换为 LocalDateTime 并将当前月份增加 3 个月时遇到问题。

这是我的代码:

String str = "13/11/2020";
LocalDateTime dateTime = LocalDateTime.parse(str, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
dateTime.plusMonths(3);      //  => output: 13/02/2021
System.out.println(dateTime);

但是当我 运行 它时,我得到以下异常:

java.time.format.DateTimeParseException: Text '13/11/2020' could not be parsed at index 2
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949) ~[?:1.8.0_144]
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851) ~[?:1.8.0_144]
at java.time.LocalDateTime.parse(LocalDateTime.java:492) ~[?:1.8.0_144]

我该如何解决这个问题?非常感谢

多个问题:

  1. 你的字符串看起来像 LocalDateLocalDateTime,它不包含时间部分
  2. 您使用的模式与您的字符串格式不同,它应该是 dd/MM/yyyydd/MM/uuuu 而不是 dd-MM-yyyy

要解析您的字符串,您需要:

LocalDate date = LocalDate.parse(str, DateTimeFormatter.ofPattern("dd/MM/uuuu"));
dateTime = dateTime.plusMonths(3);

或者如果你想要 LocalDateTime,那么你可以使用 DateTimeFormatterBuilder 和 0 来表示小时、分钟和秒:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        .appendPattern("dd/MM/uuuu")
        .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
        .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
        .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
        .toFormatter();
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
dateTime = dateTime.plusMonths(3);

结果将是这样的:2021-02-13T00:00

注意:dateTime.plusMonths(3)immutable 因此要更改值,您必须将新值分配给变量。

您的代码中存在几个问题:

  1. 您使用了错误的格式模式。如果日期字符串包含斜杠,模式字符串也应该包含斜杠:DateTimeFormatter.ofPattern("dd/MM/yyyy").

  2. 如果日期不包含时间,则使用LocalDate代替LocalDateTime

  3. plusMonths结果需要赋值给一个新的变量来获取更新后的实例。

  4. 打印预期结果时需要使用DateTimeFormatter13/02/2021,所以可以共享同一个formatter实例:

    String str = "13/11/2020";
    var dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
    var dateTime = LocalDate.parse(str, dateTimeFormatter);
    var newDateTime = dateTime.plusMonths(3); // => output: 13/02/2021
    System.out.println(newDateTime.format(dateTimeFormatter));