繁体   English   中英

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'" 2018-01-31T17:20:30Z (或"yyyy-MM-dd'T'HH:mm:ss'Z'" )格式的两个日期之间的日期+时间列表。

到目前为止,我已经能够使用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 ,将DAYS更改为MINUTES

    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);
      }
   }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM