Reputation: 119
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
Upvotes: 4
Views: 4398
Reputation: 862
I'm not sure where the problem is so maybe I misunderstood the question, but I would go with the following:
EDIT: See @isaac answer instead
public Stream<LocalDateTime> stream() {
return Stream.iterate(startDate.atStartOfDay(), d -> d.plus(60, ChronoUnit.SECONDS))
.limit(ChronoUnit.DAYS.between(startDate, endDate) + 1);
}
Upvotes: 1
Reputation: 11706
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);
}
}
Upvotes: 2
Reputation: 480
Why, just the same:
public Stream<LocalDateTime> stream() {
return Stream.iterate(startDate, d -> d.plusMinutes(1))
.limit(ChronoUnit.MINUTES.between(startDate, endDate) + 1);
}
Upvotes: 6