Is there a usablility to get all dates between two dates in the new java.time
API?
Let's say I have this part of code:
@Test public void testGenerateChartCalendarData() { LocalDate startDate = LocalDate.now(); LocalDate endDate = startDate.plusMonths(1); endDate = endDate.withDayOfMonth(endDate.lengthOfMonth()); }
Now I need all dates between startDate
and endDate
.
I was thinking to get the daysBetween
of the two dates and iterate over:
long daysBetween = ChronoUnit.DAYS.between(startDate, endDate); for(int i = 0; i <= daysBetween; i++){ startDate.plusDays(i); //...do the stuff with the new date... }
Is there a better way to get the 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.
Using JodaTime, you can get the difference between two dates in Java using the following code: Days d = Days. daysBetween(startDate, endDate). getDays();
The idea is quite simple, just use Calendar class to roll the month back and forward to create a “date range”, and use the Date. before() and Date.
Assuming you mainly want to iterate over the date range, it would make sense to create a DateRange
class that is iterable. That would allow you to write:
for (LocalDate d : DateRange.between(startDate, endDate)) ...
Something like:
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); } public List<LocalDate> toList() { //could also be built from the stream() method List<LocalDate> dates = new ArrayList<> (); for (LocalDate d = startDate; !d.isAfter(endDate); d = d.plusDays(1)) { dates.add(d); } return dates; } }
It would make sense to add equals & hashcode methods, getters, maybe have a static factory + private constructor to match the coding style of the Java time API etc.
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