Error: Text '1/31/2020' could not be parsed at index 0 while trying to parse string date

Error: Text '1/31/2020' could not be parsed at index 0 while trying to parse string date

我有一个日期字符串如下

String test Date = "1/31/2020";

我正在使用下面的代码

public static String getPeriodMonth(String periodEndDate) {
        LocalDate localDate;
        YearMonth yearMonth = null;
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
            localDate = LocalDate.parse(periodEndDate, formatter);
            yearMonth = YearMonth.from(localDate);
        }catch (Exception e) {
             LOGGER.error("Error: "+ e.getMessage() + ">>" +   e.getCause());
        }
        return yearMonth.toString();

    }

执行此代码时出现以下异常:

Error: Text '1/31/2020' could not be parsed at index 0>>null

谁能帮我看看我做错了什么?

您应该传递 01/31/2020 或将格式更新为 M/dd/yyyy

DateTimeFormatter documentation

月份被视为数字,在文档中:

Number: If the count of letters is one, then the value is output using the minimum number of digits and without padding. Otherwise, the count of digits is used as the width of the output field, with the value zero-padded as necessary.

错误是由于使用了格式字符串。 “MM”要求输入字符串的月份部分正好是两位数,但“1”只是一位数。换句话说,"MM/dd/yyyy" 适用于“01/31/2020”,但不适用于“1/31/2020”。

这里需要的不是“MM”而是“M”,它不需要值前面有“0”:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/dd/yyyy");

如果日期部分也应允许为单个数字且在第 0-9 天不使用 0 填充,则应改用 "M/d/yyyy" 模式。

DateTimeFormatter Javadocs 对此进行了描述:

All letters 'A' to 'Z' and 'a' to 'z' are reserved as pattern letters. The following pattern letters are defined:

Symbol  Meaning                     Presentation      Examples
------  -------                     ------------      -------
[...]
 M/L     month-of-year               number/text       7; 07; Jul; July; J
[...]

Text: [...]

Number: If the count of letters is one, then the value is output using the minimum number of digits and without padding. Otherwise, the count of digits is used as the width of the output field, with the value zero-padded as necessary. [...]

Number/Text: If the count of pattern letters is 3 or greater, use the Text rules above. Otherwise use the Number rules above.

由于“M”使用“number/text”表示,并且其字母在 "MM/dd/yyyy" 格式中的个数为 2("MM"),因此它需要恰好两位数字这个月。将格式切换为单个“M”会导致它使用最少的位数(1-9 个月使用一位数字,10-12 个月使用两位数字)。