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

我有一个开始时间: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 年的月份。请帮忙。


斯蒂芬大帝
浏览 203回答 1
1回答

四季花海

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

相关分类

Java