How to get dates using LocalDate.datesUntil() method in Java 9?


The LocalDate.datesUntil() method creates a stream between two local date instances and allows us to optionally specify a step size. This method has two variations, the first one takes end date and gives a list of dates between the current date and end date whereas the second one takes a Period object as a parameter that provides a way to skip dates and stream only a select subset of the dates between start and end dates.

Syntax

public Stream<LocalDate> datesUntil(LocalDate end)
public Stream<LocalDate> datesUntil(LocalDate end, Period step)

Example

import java.time.LocalDate;
import java.time.Period;
import java.time.Month;
import java.util.stream.Stream;

public class DatesUntilMethodTest {
   public static void main(String args[]) {
      final LocalDate myBirthday = LocalDate.of(1980, Month.AUGUST, 8);
      final LocalDate christmas = LocalDate.of(1980, Month.DECEMBER, 25);

      System.out.println("Day-Stream:\n");
      final Stream<LocalDate> daysUntil = myBirthday.datesUntil(christmas);
      daysUntil.skip(50).limit(10).forEach(System.out::println);

      System.out.println("\nMonth-Stream:\n");
      final Stream monthsUntil = myBirthday.datesUntil(christmas, Period.ofMonths(1));
      monthsUntil.limit(5).forEach(System.out::println);
   }
}

Output

Day-Stream:

1980-09-27
1980-09-28
1980-09-29
1980-09-30
1980-10-01
1980-10-02
1980-10-03
1980-10-04
1980-10-05
1980-10-06

Month-Stream:

1980-08-08
1980-09-08
1980-10-08
1980-11-08
1980-12-08

Updated on: 28-Feb-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements