Java 8:如何計算感恩節是哪天
這篇教程主要是讓大家了解下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:如何計算感恩節是哪天
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!