Java 8 LocalDateTime - how to get all the time between two dates

I want to generate a list of dates + times between two dates in format 2018-01-31T17:20:30Z(or "yyyy-MM-dd'T'HH:mm:ss'Z'") in increments of 60 seconds.

So far, I could generate all dates between two dates using an object 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);
  }

}

Given a start and end date, this generates Iterableall dates between them.

However, I would like to change this so that it generates every step of 60 seconds using the object LocalDateTime(i.e. instead of generating one value per day, it would generate 1440 values, because 60 minutes per hour once 24 hours a day, if the initial and the final time was only one day)

thank

+4
source share
3

LocalDate LocalDateTime Days Minutes 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);
      }
   }
+1

, :

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

I'm not sure where the problem is, so maybe I misunderstood the question, but I would go with the following:

EDIT: instead of answering @isaac's question

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

Source: https://habr.com/ru/post/1692992/


All Articles