如何使用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
我怎样才能得到一个月的第一个星期天强>
# 1 楼答案
您可以在每次迭代中添加一个月
Demo
# 2 楼答案
你可以试着移动这个
在while中,逐月更新
now
,而不是每周更新sunday
# 3 楼答案
溪流
我们可以用一条小溪在一年中的几个月里循环
^{} 类代表一年。在传递^{} 枚举对象(^{} 到} 返回^{} 对象。在传递} 返回该月第一个月的^{} 对象。我们可以使用^{} ,特别是来自^{} 的那一个,从该月的第一个
DECEMBER
)时调用^{1
时调用^{LocalDate
移动到该月的第一个星期天。我们在周日的约会中又得到了一个LocalDate
对象我们通过调用^{} 将每个月派生的第一个星期日} 的简单调用来替换该列表收集器
LocalDate
对象收集到一个列表中。在Java16及更高版本中,我们可以用对^{类似这样的代码
进口
看这个code run live at IdeOne.com