我有一个以这种方式工作的方法:以 3 个参数作为参数 - 包含日期(按升序排序)、间隔单位和间隔值的列表检查下一个元素是否不超过前一个日期(间隔)。换句话说,给定 30 分钟的间隔,上一个 - 10:00,下一个 10:29 - 进一步迭代。如果下一个是 10:31 - 打破它并返回连续日期的计数器。它的代码如下:public static void main(String[] args){ Date d1 = new Date(); Date d2 = addOrSubtractTimeUnitFromDate(d1, Calendar.MINUTE, 10, true); Date d3 = addOrSubtractTimeUnitFromDate(d2, Calendar.MINUTE, 10, true); Date d4 = addOrSubtractTimeUnitFromDate(d3, Calendar.MINUTE, 10, true); Date d5 = addOrSubtractTimeUnitFromDate(d4, Calendar.MINUTE, 10, true); Date d6 = addOrSubtractTimeUnitFromDate(d5, Calendar.MINUTE, 10, true); List<Date> threeDates = new ArrayList<>(); threeDates.add(d1); threeDates.add(d2); threeDates.add(d3); threeDates.add(d4); threeDates.add(d5); threeDates.add(d6); System.out.println(returnDatesInARowCounter(threeDates, Calendar.MINUTE, 30));}private static int returnDatesInARowCounter(List<Date> allDates, int intervalBetween2DatesTimeUnit, int intervalValue){ int datesInARowCounter = allDates.size() > 0 ? 1 : 0; // esp. this line (in case allDates is empty) Date lastDate = null; Date nextDate; Iterator<Date> iter = allDates.iterator(); while (iter.hasNext()) { nextDate = iter.next(); if (lastDate != null) // both lastDate и nextDate are initialized now { if(isNextIncidentInIntervalWithLastOneOrNot(lastDate, nextDate, intervalBetween2DatesTimeUnit, intervalValue, true)) { datesInARowCounter += 1; } else break; } lastDate = nextDate; } return datesInARowCounter;}public static Date addOrSubtractTimeUnitFromDate(Date dateToAddToOrSubtractFrom, int calendarTimeUnit, int value, boolean isAdd){ if(!isAdd) { value = -value; } Calendar cal = Calendar.getInstance(); cal.setTime(dateToAddToOrSubtractFrom); cal.add(calendarTimeUnit, value); return cal.getTime();}然而,该代码对我来说看起来很奇怪。有什么方法可以让它看起来更具可读性吗?
1 回答
qq_花开花谢_0
TA贡献1835条经验 获得超7个赞
如果您使用的是 Java 8 或更高版本,则可以改用 java.time-API。它对“时间段”的内置支持使实际实施变得更加简单。
static int daysInARow(List<Instant> allInstants, Duration maxDifference) {
int counter = allInstants.size() > 0 ? 1 : 0;
Instant previous = allInstants.get(0);
for (int i = 1; i < allInstants.size(); i++) {
Instant current = allInstants.get(i);
if (Duration.between(previous, current).compareTo(maxDifference) > 0)
break;
counter++;
previous = current;
}
return counter;
}
java.util.Date如果您在项目的其他部分使用,您可以Instant使用以下命令轻松地在 s之间进行转换
Date#from(Instant)
和
Date#toInstant()
添加回答
举报
0/150
提交
取消