以较低的特​​异性解析 ISO 日期

Parse ISO-date with lower specificity

我正在尝试解析符合 ISO8601 的字符串,这些字符串仅指定特定日期之前的日期,例如 2018-02 表示 2018 年 2 月,跳过了这一天。

java.time 包似乎无法解析此类字符串。我尝试了以下方法:

Instant.parse("2018-02");
LocalDateTime.parse("2018-02")
LocalDate.parse("2018-02", DateTimeFormatter.ISO_DATE);

失败并出现以下错误

DateTimeParseException: Text '2018-02' could not be parsed at index 7

我也尝试了以下方法,尽管我实际上并不想指定确切的模式,只是接受符合 ISO8601 的所有内容:

LocalDate.parse("2018-02", DateTimeFormatter.ofPattern("yyyy-MM"));

失败:

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

有没有办法用 java.time 包解析这样的 ISO8601 字符串?

是的,您可以使用 the YearMonth class:

YearMonth ym = YearMonth.parse("2018-02");

(输入为ISO格式,此处无需提供格式化程序)


更新

在评论中,您指出输入可以是 2018-022018-02-01,在这种情况下您希望忽略该日期。在这种情况下,您可以使用:

//note the optional day
DateTimeFormatter FMT = DateTimeFormatter.ofPattern("yyyy-MM[-dd]");

YearMonth ym = YearMonth.from(FMT.parseBest(input, YearMonth::from, LocalDate::from));