我有一个开始时间:startTime:09-2017,结束时间是endTime:05-2018。我想计算每个月的数据量,然后加起来计算从开始到结束的时间段内的数据。例如,开始时间为09-2017,结束于5-2018。在8个月的时间段内,我想计算每个月的数据,然后加起来计算所有时间段。我使用for循环结束时间减去一个月。如果endTime的月份等于monthOfStartTime,则循环将停止。我将数据保存到arrayList,一个月后,我将其添加回去。下面是我的代码:
开始时间:09-2017; 结束时间:05-2018;
@Autowired
private StudentDao studentDao;
//total students in 8 month
List<Student> students = new ArrayList<>();
//caculator data in everyMonth
for (int i = dateTimeNow.getMonthOfYear(); i >= 0; i--) {
//break if equal startTime.
LocalDateTime startTimeCaculator = endTime.getMonthOfYear().minusMonths(i-1);
List<Student> studentOnMonth =
studentDao.getDataEveryMonth(startTimeCaculator,endTime);
students.addAll(studentOnMonth);
}
我有两个问题。当我计算开始日期时,循环停止的条件是什么?其次,如果我使用i = endTime.getMonthOfYear变量,则循环将从月末开始计数到零,并且不会在多年内计数。时间到5-2018年结束,循环将运行5次,并且不会持续到2017年的几个月。请帮忙。
答案 0 :(得分:1)
您可以像这样使用isAfter()函数:
LocalDateTime endTime= ....; // 05-2018
LocalDateTime startTime= ....; // 09-2017
while(endTime.isAfter(startTime)){
endtime = endTime.minusMonths(1);
....
....
}
答案 1 :(得分:0)
我将像这样控制循环:
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