Я бы контролировал цикл следующим образом:
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
. Это будет зависеть от требуемой гибкости: передача двух экземпляров datetime допускает более короткие или более длительные периоды, чем один месяц, поэтому дает большую гибкость.
Редактировать: Если вы хотите, чтобы startMonth
был включен, используйте «не до», чтобы означать «включено» или «после», например:
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