如何使用java 8 time API获得下个月(下一个圣诞节)? [英] How to get next MonthDay (next Christmas) with java 8 time API?

查看:173
本文介绍了如何使用java 8 time API获得下个月(下一个圣诞节)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想知道在圣诞节前有多少天的方法可以在任何一年的任何一天工作,所以下一个圣诞节可能是今年或明年,我不知道它是否是闰年。

Let's say I want to know how many days are until Christmas with a method that works any day of any year so next Christmas may be this year or next year that I don't know if it is a leap year or not.

我可能会计算下一个圣诞节日期,然后计算从现在起直到那时的日期。我可以代表圣诞节作为MonthDay.of(12,25),但我找不到它有多大帮助。

I might calculate the next Christmas date and then calculate the days from now until then. I can represent Christmas Day as MonthDay.of(12, 25) but I can't find how that helps.

我发现很容易计算下一个日期星期一这样:

I found it is easy to calculate the date of next Monday this way:

    ZonedDateTime nextMonday = ZonedDateTime.now()
            .with(TemporalAdjusters.next(DayOfWeek.MONDAY))
            .truncatedTo(ChronoUnit.DAYS);

但我找不到任何TemporalAdjuster来对MonthDay做同样的事情。

But I can't find any TemporalAdjuster to do the same with MonthDay.

我找不到一个简单的方法吗?

Is there an easy way I didn't find?

推荐答案

我不认为有一个内置的时间调整器可以进入下一个月日,但你可以自己构建它:

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);
}

这篇关于如何使用java 8 time API获得下个月(下一个圣诞节)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆