已经有几个很好的答案了。请允许我看看我是否还能设计出一些优雅的东西。
只创建一个对象列表
首先,我建议你不要两个列表。这是此处描述的反模式:Anti-pattern: parallel collections。由于每个第一天都属于另一个列表中相应的最后一天,因此当您将它们放在一起时,一切都会更方便且不易出错。为此,您可以使用一些库类或设计自己的:
public class DateInterval {
LocalDate firstDay;
LocalDate lastDay;
public DateInterval(LocalDate firstDay, LocalDate lastDay) {
if (lastDay.isBefore(firstDay)) {
throw new IllegalArgumentException("Dates in wrong order");
}
this.firstDay = firstDay;
this.lastDay = lastDay;
}
// getters and other stuff
@Override
public String toString() {
return "" + firstDay + " - " + lastDay;
}
}
有了这个类,我们只需要一个列表:
LocalDate firstDayOverall = LocalDate.of(2018, Month.DECEMBER, 10);
LocalDate lastDayOverall = LocalDate.of(2019, Month.JANUARY, 6);
if (lastDayOverall.isBefore(firstDayOverall)) {
throw new IllegalStateException("Overall dates in wrong order");
}
LocalDate firstDayOfLastMonth = lastDayOverall.withDayOfMonth(1);
LocalDate currentFirstDay = firstDayOverall;
List<DateInterval> intervals = new ArrayList<>();
while (currentFirstDay.isBefore(firstDayOfLastMonth)) {
intervals.add(new DateInterval(currentFirstDay, currentFirstDay.with(TemporalAdjusters.lastDayOfMonth())));
currentFirstDay = currentFirstDay.withDayOfMonth(1).plusMonths(1);
}
intervals.add(new DateInterval(currentFirstDay, lastDayOverall));
System.out.println("Intervals: " + intervals);
上述代码sn-p的输出为:
间隔:[2018-12-10 - 2018-12-31, 2019-01-01 - 2019-01-06]
第一天和最后一天在同一个月的特殊情况由根本不循环的循环和循环后的add 处理,将单个间隔添加到列表中。
如果需要两个日期列表
如果您确实坚持使用两个列表,则两个参数 datesUntil 方法很方便:
List<LocalDate> firstDays = new ArrayList<>();
firstDays.add(firstDayOverall);
// first day not to be included in first days
LocalDate endExclusive = lastDayOverall.withDayOfMonth(1).plusMonths(1);
List<LocalDate> remainingFirstDays = firstDayOverall.withDayOfMonth(1)
.plusMonths(1)
.datesUntil(endExclusive, Period.ofMonths(1))
.collect(Collectors.toList());
firstDays.addAll(remainingFirstDays);
System.out.println("First days: " + firstDays);
// Calculate last days as the day before each first day except the first
List<LocalDate> lastDays = remainingFirstDays.stream()
.map(day -> day.minusDays(1))
.collect(Collectors.toCollection(ArrayList::new));
lastDays.add(lastDayOverall);
System.out.println("Last days: " + lastDays);
输出:
First days: [2018-12-10, 2019-01-01]
Last days: [2018-12-31, 2019-01-06]
一边
起初我觉得YearMonth 类会是一个优雅的解决方案。然而,我意识到它需要对第一个月和上个月进行特殊处理,所以我认为它不会产生比我们上面的代码更优雅的代码。喜欢的可以试试。