Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 LocalDate - How do I get all dates between two dates?

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?

like image 516
Patrick Avatar asked Jul 06 '16 09:07

Patrick


People also ask

How do I generate all 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 can I get the difference between two dates in Java 8?

Using JodaTime, you can get the difference between two dates in Java using the following code: Days d = Days. daysBetween(startDate, endDate). getDays();

How do you create a date range in Java?

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.


1 Answers

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.

like image 54
assylias Avatar answered Sep 18 '22 23:09

assylias