How to get next MonthDay (next Christmas) with java 8 time API?

蹲街弑〆低调 提交于 2019-12-04 16:14:10

I don't think there is a built-in temporal adjuster to go to the next "MonthDay" but you can build it yourself:

public static void main(String[] args) {
  MonthDay XMas = MonthDay.of(DECEMBER, 25);
  System.out.println(LocalDate.of(2014, DECEMBER, 5).with(nextMonthDay(XMas)));
  System.out.println(LocalDate.of(2014, DECEMBER, 26).with(nextMonthDay(XMas)));
}

public static TemporalAdjuster nextMonthDay(MonthDay monthDay) {
  return (temporal) -> {
    int day = temporal.get(DAY_OF_MONTH);
    int month = temporal.get(MONTH_OF_YEAR);
    int targetDay = monthDay.getDayOfMonth();
    int targetMonth = monthDay.getMonthValue();
    return MonthDay.of(month, day).isBefore(monthDay)
            ? temporal.with(MONTH_OF_YEAR, targetMonth).with(DAY_OF_MONTH, targetDay)
            : temporal.with(MONTH_OF_YEAR, targetMonth).with(DAY_OF_MONTH, targetDay).plus(1, YEARS);
}

I am using the following temporal adjusters:

public static TemporalAdjuster nextOrSame(MonthDay monthDay) {
    return temporal -> monthDay.adjustInto(temporal).plus(MonthDay.from(temporal).compareTo(monthDay) > 0 ? 1 : 0, YEARS);
}

public static TemporalAdjuster previousOrSame(MonthDay monthDay) {
    return temporal -> monthDay.adjustInto(temporal).minus(MonthDay.from(temporal).compareTo(monthDay) < 0 ? 1 : 0, YEARS);
}

Here is a method that creates a temporal adjuster given a MonthDay, just like the one of assylias but code is different. I think both work.

private static TemporalAdjuster nextMonthDayAdjuster(final MonthDay md) {
    return (Temporal d) -> {
        Function<Integer, Temporal> dateOnYear = year -> md.atYear(year).adjustInto(d);
        int year = d.get(ChronoField.YEAR);
        Temporal dateThatYear = dateOnYear.apply(year);
        if (d.until(dateThatYear, ChronoUnit.NANOS) > 0L) {
            return dateThatYear;
        } else {
            return dateOnYear.apply(year + 1);
        }
    };
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!