我想要一个开始日期和结束日期之间的日期列表,但是要有间隔选项,
如果我选择30,则获取Java中间隔30分钟的日期列表。
例如,从01/01/2018 10:00到02/01/2018 10:00应该给出
有人可以帮助我吗?
谢谢!
答案 0 :(得分:1)
从开始日期开始。然后向其添加时间间隔,直到达到结束日期。
示例:
public static Iterator<LocalDateTime> datesBetween(LocalDateTime start, LocalDateTime end, int periodInMinutes) {
return new DatesBetweenIterator(start, end, periodInMinutes);
}
private static class DatesBetweenIterator implements Iterator<LocalDateTime> {
private LocalDateTime nextDate;
private final LocalDateTime end;
private final int periodInMinutes;
private DatesBetweenIterator(LocalDateTime start, LocalDateTime end, int periodInMinutes) {
this.nextDate = start;
this.end = end;
this.periodInMinutes = periodInMinutes;
}
@Override
public boolean hasNext() {
return nextDate.isBefore(end);
}
@Override
public LocalDateTime next() {
LocalDateTime toReturn = nextDate;
nextDate = nextDate.plusMinutes(periodInMinutes);
return toReturn;
}
}