我会像这样控制循环:
YearMonth endMonth = YearMonth.of(2018, Month.MAY);
YearMonth startMonth = YearMonth.of(2017, Month.SEPTEMBER);
for (YearMonth m = endMonth; m.isAfter(startMonth); m = m.minusMonths(1)) {
LocalDateTime monthStart = m.atDay(1).atStartOfDay();
LocalDateTime monthEnd = m.plusMonths(1).atDay(1).atStartOfDay();
System.out.println("Month from " + monthStart + " inclusive to " + monthEnd + " exclusive");
}
由于代码片段在此处输出:
Month from 2018-05-01T00:00 inclusive to 2018-06-01T00:00 exclusive
Month from 2018-04-01T00:00 inclusive to 2018-05-01T00:00 exclusive
Month from 2018-03-01T00:00 inclusive to 2018-04-01T00:00 exclusive
Month from 2018-02-01T00:00 inclusive to 2018-03-01T00:00 exclusive
Month from 2018-01-01T00:00 inclusive to 2018-02-01T00:00 exclusive
Month from 2017-12-01T00:00 inclusive to 2018-01-01T00:00 exclusive
Month from 2017-11-01T00:00 inclusive to 2017-12-01T00:00 exclusive
Month from 2017-10-01T00:00 inclusive to 2017-11-01T00:00 exclusive
如果它不是您想要的,请调整 .
您可能还想修改学生DAO以接受 YearMonth 参数 . 这取决于您想要的灵活性:传递两个日期时间实例允许比一个月更短或更长的时间段,因此提供了更大的灵活性 .
编辑:如果您想要包含 startMonth ,请使用“not before”表示或之后,例如:
YearMonth endMonth = YearMonth.of(2017, Month.OCTOBER);
YearMonth startMonth = YearMonth.of(2017, Month.SEPTEMBER);
for (YearMonth m = endMonth; ! m.isBefore(startMonth); m = m.minusMonths(1)) {
LocalDateTime monthStart = m.atDay(1).atStartOfDay();
LocalDateTime monthEnd = m.plusMonths(1).atDay(1).atStartOfDay();
System.out.println("Month from " + monthStart + " inclusive to " + monthEnd + " exclusive");
}
输出:
Month from 2017-10-01T00:00 inclusive to 2017-11-01T00:00 exclusive
Month from 2017-09-01T00:00 inclusive to 2017-10-01T00:00 exclusive