gpt4 book ai didi

java - TemporalAdjuster - 从调整后的日期获取下一个日期

转载 作者:行者123 更新时间:2023-12-02 08:52:53 25 4
gpt4 key购买 nike

假设我有一个自定义的TemporalAdjuster,它会在每个星期日(也可能是每个第二个星期二等)给我一个时间。如何计算一年中所有调整后的日期?

TemporalAdjuster myGamingAdjuster;
int myYear = 2003;
LocalDate myDate = LocalDate.now();
System.out.println(myDate.with(myGamingAdjuster)); // Gives only one date

最佳答案

您可以创建一个自定义方法,根据问题中的两个需求生成您期望的内容,您可以创建如下方法:

public List<LocalDate> generateDates(int year, int periodicDays, DayOfWeek startDay){
LocalDate firstDay = LocalDate.of(year, Month.JANUARY, 1)
.with(TemporalAdjusters.next(startDay));
List<LocalDate> result = new ArrayList<>();
do {
result.add(firstDay);
firstDay = firstDay.plusDays(periodicDays);
} while (firstDay.getYear() == year);
return result;
}

然后,像这样调用你的方法:

List<LocalDate> allSunDaysInYear = generateDates(2003, 7, DayOfWeek.SUNDAY)
List<LocalDate> allEvrySeconTuesdaysInYear = generateDates(2003, 14, DayOfWeek.MONDAY);

输出

[2003-01-05, 2003-01-12, 2003-01-19, 2003-01-26, 2003-02-02, 2003-02-09, ..]
[2003-01-06, 2003-01-20, 2003-02-03, 2003-02-17, 2003-03-03, 2003-03-17, ..]

关于java - TemporalAdjuster - 从调整后的日期获取下一个日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60672808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com