解析具有较低特异性的ISO日期

时间:2018-02-15 10:39:39

标签: java java-time iso8601 localdate

我正在尝试解析符合ISO8601标准的字符串,该字符串仅指定特定点的日期,例如2018年2月的2018-02,跳过这一天。

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

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

失败并出现以下错误

  

DateTimeParseException:无法在索引7处解析文本“2018-02”

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

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

失败了:

  

java.time.format.DateTimeParseException:无法解析文本'2018-02':无法从TemporalAccessor获取LocalDate:{MonthOfYear = 2,Year = 2018},ISO类型为java.time.format.Parsed < / p>

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

1 个答案:

答案 0 :(得分:3)

是的,您可以使用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));