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

David Lynch :

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

So far I've been able to generate all dates between two dates using a LocalDate object:

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 an Iterable of all dates in between.

However, I would like modify this so that it generates each time in 60 second increments using LocalDateTime object (i.e, instead of generating one value per day it would generate 1440 values as there are 60 minutes per hour times 24 hrs per day assuming the start and end time was only one day)

Thanks

Sahil Chhabra :

Just change the LocalDate to LocalDateTime and plusDays to plusMinutes and DAYS to 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);
      }
   }

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=476205&siteId=1