Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 828
David Lynch Avatar asked Jan 31 '18 17:01

David Lynch


People also ask

How can we get duration between two dates or time in Java 8?

In Java 8, we can use Period , Duration or ChronoUnit to calculate the difference between two LocalDate or LocaldateTime . Period to calculate the difference between two LocalDate . Duration to calculate the difference between two LocalDateTime . ChronoUnit for everything.

How can I get a list of dates between two dates?

We can get the dates between two dates with single method call using the dedicated datesUntil method of a LocalDate class. The datesUntill returns the sequentially ordered Stream of dates starting from the date object whose method is called to the date given as method argument.

How do I find the difference between two dates in LocalDate?

The Period class has a between() method - just as the previously discussed ChronoUnit . This method takes in two LocalDate objects, one representing the starting date, and the second being the end date. It returns a Period consisting of the number of years, months, and days between two dates.

What is the difference between date and LocalDateTime in Java?

LocalDate is the date the calendar on the wall says. java. util. Date is not a date, it's an instant, and actually represents a millisecond offset from Unix epoch.


1 Answers

Why, just the same:

public Stream<LocalDateTime> stream() {
    return Stream.iterate(startDate, d -> d.plusMinutes(1))
                 .limit(ChronoUnit.MINUTES.between(startDate, endDate) + 1);
}
like image 66
cosh Avatar answered Sep 20 '22 19:09

cosh