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
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.
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.
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.
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.
Why, just the same:
public Stream<LocalDateTime> stream() {
return Stream.iterate(startDate, d -> d.plusMinutes(1))
.limit(ChronoUnit.MINUTES.between(startDate, endDate) + 1);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With