1 回答
TA贡献1811条经验 获得超5个赞
我会像这样控制循环:
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被包括在内,请使用“不在之前”来表示在或之后,例如:
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
添加回答
举报