在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

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

2016-12-20 13:13| 发布者: zhangjf| 查看: 635| 评论: 0

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

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

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

  1. import java.time.DayOfWeek;
  2. import java.time.LocalDate;
  3. import java.time.Month;
  4. import java.time.temporal.Temporal;
  5. import java.time.temporal.TemporalAdjuster;
  6. import java.time.temporal.TemporalAdjusters;
  7. // 在美国,每年11月的第4个星期四是感恩节
  8. public class ThanksGivingDayTemporalAdjuster implements TemporalAdjuster {
  9. @Override
  10. public Temporal adjustInto(Temporal temporalAdjusterInput) {
  11. LocalDate temporalAdjusterDate = LocalDate.from(temporalAdjusterInput);
  12. LocalDate firstNovInYear = LocalDate.of(temporalAdjusterDate.getYear(),
  13. Month.NOVEMBER, 1);
  14. // adjusting four weeks for Thursday
  15. LocalDate thanksGivingDay = firstNovInYear
  16. .with(TemporalAdjusters.nextOrSame(DayOfWeek.THURSDAY))
  17. .with(TemporalAdjusters.next(DayOfWeek.THURSDAY))
  18. .with(TemporalAdjusters.next(DayOfWeek.THURSDAY))
  19. .with(TemporalAdjusters.next(DayOfWeek.THURSDAY));
  20. return thanksGivingDay;
  21. }
  22. public static void main(String... strings) {
  23. LocalDate currentDate = LocalDate.now();
  24. ThanksGivingDayTemporalAdjuster thanksGivingDayAdjuster = new ThanksGivingDayTemporalAdjuster();
  25. LocalDate thanksGivingDay = currentDate.with(thanksGivingDayAdjuster);
  26. System.out.println("In Year " + currentDate.getYear()
  27. + ", Thanks Giving Day(US) is on " + thanksGivingDay);
  28. }
  29. }
复制代码

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

示例程序输出
  1. In Year 2014, Thanks Giving Day(US) is on 2014-11-27
复制代码

原创文章转载请注明出处:Java 8:如何计算感恩节是哪天

英文原文链接



最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-8 03:14

Copyright 2015-2025 djqfx

返回顶部