如何使用java获得一个月的第一个星期日
我试图得到一个月的第一个星期日。我达到的是获得一年中的所有星期日
import static java.time.temporal.TemporalAdjusters.firstInMonth;
public static void FindAllSundaysOfTheYear () {
// Create a LocalDate object that represent the first day of the year.
int year = 2021;
LocalDate now = LocalDate.of(year, Month.JANUARY, 1);
// Find the first Sunday of the year
LocalDate sunday = now.with(firstInMonth(DayOfWeek.SUNDAY));
do {
// Loop to get every Sunday by adding Period.ofDays(7) the the current Sunday.
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
回答
您可以在每次迭代中添加一个月。
public static void findFirstSundayEachMonth() {
int year = 2021;
LocalDate curr = LocalDate.of(year, Month.JANUARY, 1);
do {
System.out.println(curr.with(TemporalAdjusters.firstInMonth(DayOfWeek.SUNDAY))
.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)));
curr = curr.plusMonths(1);
} while (curr.getYear() == year);
}
Demo