使用 DateTimeFormatterBuilder 解析缺少日期的日期,默认为月末

Use DateTimeFormatterBuilder for parsing dates of missing day and default to end of month

我需要解析各种格式的日期。其中一些缺少 "day"。现在我想默认为月底。我不确定是否有一种直接的方法可以让我们默认到月末

DateTimeFormatter f = new DateTimeFormatterBuilder()
        .appendPattern("MM.yyyy")
        .parseDefaulting(DAY_OF_MONTH, 1) // can we default to end of month?
        .toFormatter();

LocalDate.parse("11.2017", f)

但如果不是,我怎么知道原来的日期少了一天(或者使用了默认日期),因此我需要使用 LocalDate.parse("11.2017", f).with(TemporalAdjusters.lastDayOfMonth()).

手动调整它
DateTimeFormatter f = new DateTimeFormatterBuilder()
      .appendPattern("MM.yyyy")
      .parseDefaulting(DAY_OF_MONTH, 31) // set 31
      .toFormatter();

只需将DAY_OF_MONTH设置为31DAY_OF_MONTH会根据rangeUnit选择最后一天 24=]解析月.

/**
 * The day-of-month.
 * <p>
 * This represents the concept of the day within the month.
 * In the default ISO calendar system, this has values from 1 to 31 in most months.
 * April, June, September, November have days from 1 to 30, while February has days
 * from 1 to 28, or 29 in a leap year.
 * <p>
 * Non-ISO calendar systems should implement this field using the most recognized
 * day-of-month values for users of the calendar system.
 * Normally, this is a count of days from 1 to the length of the month.
 */
DAY_OF_MONTH("DayOfMonth", DAYS, MONTHS, ValueRange.of(1, 28, 31), "day"),

示例:

LocalDate parse = LocalDate.parse("02.2017", f);
System.out.println(parse.getDayOfMonth());

输出:

28