我有一个函数,它应该返回一个基于startDate - endDate范围的日期列表(java.sql.Date)。我首先添加了startDate,并希望将其递增( +1天、周或月),然后从“最新”日期一直到到达endDate。
我试过使用传统的foreach,它不起作用,因为它不允许在迭代时添加新的日期,所以我切换到ListIterator。这只进入while一次,递增日期,添加日期,但显然没有next,因为add函数没有将项目附加到末尾(?)
解决这项任务的实际方法是什么?
public List<Date> getBookingDatesInRange(Date startDate, Date endDate, boolean isDaily, boolean isWeekly) {
List<Date> dates = new ArrayList<Date>();
dates.add(startDate);
ListIterator<Date> iter = dates.listIterator();
while(iter.hasNext()) {
LocalDate new = iter.next().toLocalDate();
Date newDate;
if(isDaily) {
newDate= Date.valueOf(new.plusDays(1));
} else if(isWeekly) {
newDate= Date.valueOf(new.plusWeeks(1));
} else {
newDate= Date.valueOf(new.plusMonths(1));
}
if(newDate.before(endDate) || newDate.equals(endDate) {
iter.add(newDate);
} else {
return dates;
}
}发布于 2018-12-14 00:28:05
为什么要做基于迭代器的while循环呢?仅仅基于您在迭代期间所做的日期检查不是更符合逻辑吗?
public static List<Date> getBookingDatesInRange(Date startDate, Date endDate, boolean isDaily, boolean isWeekly) {
List<Date> dates = new ArrayList<>();
dates.add(startDate);
Date newDate = startDate;
while(newDate.before(endDate) || newDate.equals(endDate)) {
if(isDaily) {
newDate = Date.valueOf(newDate.toLocalDate().plusDays(1));
} else if(isWeekly) {
newDate = Date.valueOf(newDate.toLocalDate().plusWeeks(1));
} else {
newDate = Date.valueOf(newDate.toLocalDate().plusMonths(1));
}
dates.add(newDate);
}
}
return dates;
}https://stackoverflow.com/questions/53765910
复制相似问题