Java 8 LocalDateTime - 如何获取两个日期之间的所有时间

Java 8 LocalDateTime - How to Get All Times Between Two Dates

我想以 2018-01-31T17:20:30Z(或 "yyyy-MM-dd'T'HH:mm:ss'Z'")格式以 60 秒为增量生成两个日期之间的日期和时间列表。

到目前为止,我已经能够使用 LocalDate 对象生成两个日期之间的所有日期:

public class DateRange implements Iterable<LocalDate> {


  private final LocalDate startDate;
  private final LocalDate endDate;

  public DateRange(LocalDate startDate, LocalDate endDate) {
    //check that range is valid (null, start < end)
    this.startDate = startDate;
    this.endDate = endDate;
  }


@Override
public Iterator<LocalDate> iterator() {

    return stream().iterator();
}

public Stream<LocalDate> stream() {
    return Stream.iterate(startDate, d -> d.plusDays(1))
                 .limit(ChronoUnit.DAYS.between(startDate, endDate) + 1);
  }

}

给定开始日期和结束日期,这会生成中间所有日期的 Iterable

但是,我想修改它,以便它使用 LocalDateTime 对象每次以 60 秒的增量生成(即,不是每天生成一个值,而是生成 1440 个值,因为每天有 60 分钟假设开始和结束时间只有一天,每天 24 小时)

谢谢

为什么,还是一样:

public Stream<LocalDateTime> stream() {
    return Stream.iterate(startDate, d -> d.plusMinutes(1))
                 .limit(ChronoUnit.MINUTES.between(startDate, endDate) + 1);
}

我不确定问题出在哪里,所以也许我误解了这个问题,但我会采用以下方法:

编辑:改为查看@isaac 的回答

public Stream<LocalDateTime> stream() {
    return Stream.iterate(startDate.atStartOfDay(), d -> d.plus(60, ChronoUnit.SECONDS))
        .limit(ChronoUnit.DAYS.between(startDate, endDate) + 1);
}

只需将 LocalDate 更改为 LocalDateTime 并将 plusDays 更改为 plusMinutes 分钟

    public class DateTimeRange implements Iterable<LocalDateTime> {


      private final LocalDateTime startDateTime;
      private final LocalDateTime endDateTime;

      public DateTimeRange(LocalDateTime startDateTime, LocalDateTime endDateTime) {
        //check that range is valid (null, start < end)
        this.startDateTime = startDateTime;
        this.endDateTime = endDateTime;
      }


      @Override
      public Iterator<LocalDateTime> iterator() {
         return stream().iterator();
      }

      public Stream<LocalDateTime> stream() {
         return Stream.iterate(startDateTime, d -> d.plusMinutes(1))
                     .limit(ChronoUnit.MINUTES.between(startDateTime, endDateTime) + 1);
      }
   }