如何在范围内计算每个月的数据,如果知道时间,则添加到一个列表中



>我有一个开始时间:开始时间:09-2017,结束时间是结束时间:05-2018。我想计算每个月的数据量,然后加起来计算从开始到结束期间的数据。例如,开始时间为 09-2017,结束于 5-2018。在 8 个月期间,我想计算每个月的数据,然后加起来计算所有时间段。我使用 for 循环表示结束时间减去一个月。如果结束时间的月份等于开始时间的月份,循环将停止。我将数据保存到 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 年的月份。请帮忙。

你可以像这样使用 isAfter(( 函数:

LocalDateTime endTime= ....; // 05-2018
LocalDateTime startTime= ....; // 09-2017
while(endTime.isAfter(startTime)){
endtime = endTime.minusMonths(1);
....
....
}

我会像这样控制循环:

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

最新更新