51dev.com IT技术开发者社区

51dev.com 技术开发者社区

用java实现计算感恩节是哪天

IT猿阅读(54)2019-11-20 收藏0次评论

怎样通过TemporalAdjuster来找出指定的一年中感恩节是哪天?下面是JAVA实现的代码

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;

// 在美国,每年11月的第4个星期四是感恩节
public class ThanksGivingDayTemporalAdjuster implements TemporalAdjuster {

    @Override
    public Temporal adjustInto(Temporal temporalAdjusterInput) {
        LocalDate temporalAdjusterDate = LocalDate.from(temporalAdjusterInput);
        LocalDate firstNovInYear = LocalDate.of(temporalAdjusterDate.getYear(),
                Month.NOVEMBER, 1);

        // adjusting four weeks for Thursday
        LocalDate thanksGivingDay = firstNovInYear
                .with(TemporalAdjusters.nextOrSame(DayOfWeek.THURSDAY))
                .with(TemporalAdjusters.next(DayOfWeek.THURSDAY))
                .with(TemporalAdjusters.next(DayOfWeek.THURSDAY))
                .with(TemporalAdjusters.next(DayOfWeek.THURSDAY));
        return thanksGivingDay;
    }

    public static void main(String... strings) {
        LocalDate currentDate = LocalDate.now();
        ThanksGivingDayTemporalAdjuster thanksGivingDayAdjuster = new ThanksGivingDayTemporalAdjuster();
        LocalDate thanksGivingDay = currentDate.with(thanksGivingDayAdjuster);
        System.out.println("In Year " + currentDate.getYear()
                + ", Thanks Giving Day(US) is on " + thanksGivingDay);

    }
}

每年11月的第4个星期四是感恩节。代码中的TemporalAdjuster首先将月份调整到了11月,然后连续四次将日期调整为下一个星期四。

程序输出结果:

In Year 2014, Thanks Giving Day(US) is on 2014-11-27

 

以上就是用java实现计算感恩节是哪天的全部内容。