import java.time.LocalDate;
import java.time.DayOfWeek;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;
class WeekRange {
private LocalDate startDate;
private LocalDate endDate;
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
public WeekRange(LocalDate startDate, LocalDate endDate) {
this.startDate = startDate;
this.endDate = endDate;
}
public LocalDate getStartDate() {
return startDate;
}
public LocalDate getEndDate() {
return endDate;
}
@Override
public String toString() {
return "WeekRange{" +
"startDate=" + startDate.format(formatter) +
", endDate=" + endDate.format(formatter) +
'}';
}
}
public class WeekRangeCalculator {
public static List<WeekRange> getWeekRanges(String start, String end) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate startDate = LocalDate.parse(start, formatter);
LocalDate endDate = LocalDate.parse(end, formatter);
List<WeekRange> weekRanges = new ArrayList<>();
// 找到第一个开始日期的周一
LocalDate currentStart = startDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
// 找到最后一个结束日期的周日
LocalDate finalEnd = endDate.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
while (!currentStart.isAfter(finalEnd)) {
LocalDate currentEnd = currentStart.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
weekRanges.add(new WeekRange(currentStart, currentEnd));
// 下一个周的开始日期
currentStart = currentStart.plusWeeks(1);
}
return weekRanges;
}
public static void main(String[] args) {
String start = "20260801";
String end = "20260831";
List<WeekRange> weekRanges = getWeekRanges(start, end);
for (WeekRange range : weekRanges) {
System.out.println(range);
}
}
}