如何获得Java中一年中的所有星期日?
您需要为您的应用程序创建一个假日日历。其中一个功能是将一年中的所有星期天都作为日历中的一个节日。下面的代码片段将向您展示如何获得给定年份的所有星期天。首先,我们需要使用 main()方法中的前3行代码来查找一年中的第一个星期天。在获得第一个星期天之后,我们只需要循环使用Period.ofDays ()将7天添加到当前的星期天,以获得下一个星期天。当星期天的年份与现在的年份不同时,我们就停止循环。
package org.nhooo.example.datetime;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import static java.time.temporal.TemporalAdjusters.firstInMonth;
public class FindAllSundaysOfTheYear {
public static void main(String[] args) {
// 创建代表一年中第一天的LocalDate对象。
int year = 2020;
LocalDate now = LocalDate.of(year, Month.JANUARY, 1);
// 查找一年中的第一个星期日
LocalDate sunday = now.with(firstInMonth(DayOfWeek.SUNDAY));
do {
// 通过将Period.ofDays(7)添加到当前星期日来循环获取每个星期日。
System.out.println(sunday.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)));
sunday = sunday.plus(Period.ofDays(7));
} while (sunday.getYear() == year);
}
}此代码段的输出为:
Sunday, January 5, 2020 Sunday, January 12, 2020 Sunday, January 19, 2020 Sunday, January 26, 2020 Sunday, February 2, 2020 Sunday, February 9, 2020 Sunday, February 16, 2020 Sunday, February 23, 2020 ... Sunday, December 6, 2020 Sunday, December 13, 2020 Sunday, December 20, 2020 Sunday, December 27, 2020
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短