假设我有一个自定义的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, ..]

10-08 16:10