Java 8:如何计算感恩节是哪天

jopen 10年前

这篇教程主要是让大家了解下Java 8的时间及日期API中新引入的时间调节器(TemporalAdjuster)。在前一篇教程中我们已经对这套新的API以及TemporalAdjuster的用法作了一个简单的介绍。

在这篇教程中,我们来看下如何通过TemporalAdjuster来查找出指定的一年中感恩节是哪天。

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 8:如何计算感恩节是哪天

英文原文链接