为什么我的模式 ("yyyyMM") 无法使用 DateTimeFormatter (java 8) 进行解析

Why my pattern("yyyyMM") cannot parse with DateTimeFormatter (java 8)

当我使用SimpleDateFormat时,它可以解析。

SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
format.setLenient(false);
Date d = format.parse(date);

但是当我使用 Java 8 DateTimeFormatter,

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
LocalDate localDate = LocalDate.parse(date, formatter);

它抛出

java.time.format.DateTimeParseException: Text '201510' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {Year=2015, MonthOfYear=10},ISO of type java .time.format.Parsed

日期的字符串值为 "201510"

问自己一个问题:应该用字符串 "201510" 解析哪一天? LocalDate 需要一天,但由于日期中没有日期要解析,因此无法构造 LocalDate 的实例。

如果只想解析年和月,可以使用YearMonth对象代替:

YearMonth localDate = YearMonth.parse(date, formatter);

但是,如果您真的想从此字符串中解析出 LocalDate,您可以构建自己的 DateTimeFormatter,以便它使用月份的第一天作为默认值:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                                .appendPattern("yyyyMM")
                                .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
                                .toFormatter();
LocalDate localDate = LocalDate.parse(date, formatter);

您可以使用 YearMonth 并指定您想要的日期(例如第一天):

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
LocalDate localDate = YearMonth.parse(date, formatter).atDay(1);

或者如果日期无关紧要,只需使用 YearMonth