66

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?

Patrick
  • 12,336
  • 15
  • 73
  • 115
  • You could as well increment the startdate as long as it is smaller than enddate. (Assuming start is always smaller than end to begin with.) – Fildor Jul 06 '16 at 09:30
  • I don't think there is an other way than iterate. – J.Mengelle Jul 06 '16 at 09:31
  • I could imagine there might be some fancy Java8 stream - way to get a list of those dates ... but I am not too familiar with that new API. – Fildor Jul 06 '16 at 09:32
  • 1
    Possible duplicate of [how to get a list of dates between two dates in java](http://stackoverflow.com/questions/2689379/how-to-get-a-list-of-dates-between-two-dates-in-java) – Thermech Dec 07 '16 at 15:39

8 Answers8

98

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.

assylias
  • 321,522
  • 82
  • 660
  • 783
  • 2
    Its a clean approach to have the logic in an own class. Thanks for pointing me in this direction! – Patrick Jul 06 '16 at 14:18
  • @Flown I could (see the comment on the toList method). This is an extract from a larger class and I think the reason not to was performance (not sure if it makes a real difference to be honest). – assylias Jul 07 '16 at 08:08
  • @assylias I saw the comment later and deleted my comment. Do you really think performance is an issue in this case? – Flown Jul 07 '16 at 08:23
  • @Flown To be tested ;-) – assylias Jul 07 '16 at 09:44
  • 2
    `LongStream.rangeClosed(0, ChronoUnit.DAYS.between(startDate, endDate)) .mapToObj(startDate::plusDays)`… – Holger Sep 26 '18 at 12:02
  • 1
    A bit of both, though readability is subjective. But it creates a sized stream, which may have slight advantages when iterating, but significant ones with operations like `toArray`, `count()` (obviously), and with parallel streams. And it’s closer to the OP’s original loop. – Holger Sep 26 '18 at 13:04
  • This is the best answer for this case because you won't have to deal with final variables like you would have to if you used the stream approach. – Dalton Mar 19 '19 at 13:16
83

First you can use a TemporalAdjuster to get the last day of the month. Next the Stream API offers Stream::iterate which is the right tool for your problem.

LocalDate start = LocalDate.now();
LocalDate end = LocalDate.now().plusMonths(1).with(TemporalAdjusters.lastDayOfMonth());
List<LocalDate> dates = Stream.iterate(start, date -> date.plusDays(1))
    .limit(ChronoUnit.DAYS.between(start, end))
    .collect(Collectors.toList());
System.out.println(dates.size());
System.out.println(dates);
Flown
  • 11,480
  • 3
  • 45
  • 62
  • 1
    Thanks for your very good solution. Would use it when I still need the List. – Patrick Jul 06 '16 at 09:45
  • 2
    @Patrick you didn't specify how the results should look like, it was only an assumption. You also don't have to store the results, instead you can use [`Stream::forEach`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#forEach-java.util.function.Consumer-) to process the results. – Flown Jul 06 '16 at 09:48
  • 4
    It should be `.limit(ChronoUnit.DAYS.between(start, end) + 1)` to include the last day of each month. – user405935 Jul 30 '17 at 08:53
  • @user405935 This question is more than a year old and should outline a solution. It is left to the user to adapt this snippet to fit the requirements. – Flown Jul 30 '17 at 18:33
  • Whoa! I was able to replace a huge `do...while` with this trick. Thanka a lot. – riccardo.cardin Nov 24 '17 at 13:58
  • Thanks for such an elegant solution – Sviatlana Oct 03 '19 at 15:28
62

Java 9

In Java 9, the LocalDate class was enhanced with the LocalDate.datesUntil(LocalDate endExclusive) method, which returns all dates within a range of dates as a Stream<LocalDate>.

List<LocalDate> dates = startDate.datesUntil(endDate).collect(Collectors.toList());
M. Justin
  • 14,487
  • 7
  • 91
  • 130
Durgpal Singh
  • 11,481
  • 4
  • 37
  • 49
10

tl;dr

Expanding on the good Answer by Singh, using a stream from datesUntil in Java 9 and later.

today                                 // Determine your beginning `LocalDate` object.
.datesUntil(                          // Generate stream of `LocalDate` objects.
    today.plusMonths( 1 )             // Calculate your ending date, and ask for a stream of dates till then.
)                                     // Returns the stream.
.collect( Collectors.toList() )       // Collect your resulting dates in a `List`. 
.toString()                           // Generate text representing your found dates.

[2018-09-20, 2018-09-21, 2018-09-22, 2018-09-23, 2018-09-24, 2018-09-25, 2018-09-26, 2018-09-27, 2018-09-28, 2018-09-29, 2018-09-30, 2018-10-01, 2018-10-02, 2018-10-03, 2018-10-04, 2018-10-05, 2018-10-06, 2018-10-07, 2018-10-08, 2018-10-09, 2018-10-10, 2018-10-11, 2018-10-12, 2018-10-13, 2018-10-14, 2018-10-15, 2018-10-16, 2018-10-17, 2018-10-18, 2018-10-19]

LocalDate::datesUntil stream

As of Java 9, you can ask for a stream of dates. Call LocalDate::datesUntil.

Start by determining today's date. That requires a time zone. For any given moment, the date varies around the globe by zone.

ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
LocalDate today = LocalDate.now( z ) ;

Determine your ending date.

LocalDate stop = today.plusMonths( 1 ) ;

Ask for stream of dates from beginning to ending.

Stream< LocalDate > stream = today.datesUntil( today.plusMonths( 1 ) );

Pull the dates from that stream, collecting them into a List.

List< LocalDate > datesForMonthFromToday = stream.collect( Collectors.toList() );

Print our list of dates, generating text in standard ISO 8601 format.

System.out.println( datesForMonthFromToday );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

M. Justin
  • 14,487
  • 7
  • 91
  • 130
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
6

You could create a stream of LocalDate objects. I had this problem too and I published my solution as java-timestream on github.

Using your example...

LocalDateStream
    .from(LocalDate.now())
    .to(1, ChronoUnit.MONTHS)
    .stream()
    .collect(Collectors.toList());

It's more or less equivalent to other solutions proposed here, but it takes care of all of the date math and knowing when to stop. You can provide specific or relative end dates, and tell it how much time to skip each iteration (the default above is one day).

Todd
  • 30,472
  • 11
  • 81
  • 89
4

The ThreeTen-Extra library has a LocalDateRange class that can do exactly what you're requesting:

LocalDateRange.ofClosed(startDate, endDate).stream()
        .forEach(/* ...do the stuff with the new date... */);
M. Justin
  • 14,487
  • 7
  • 91
  • 130
2

You could use the Range functionality in Google's Guava library. After defining the DiscreteDomain over LocalDate instances you could get a ContiguousSet of all dates in the range.

LocalDate d1 = LocalDate.parse("2017-12-25");
LocalDate d2 = LocalDate.parse("2018-01-05");

DiscreteDomain<LocalDate> localDateDomain = new DiscreteDomain<LocalDate>() {
    public LocalDate next(LocalDate value) { return value.plusDays(1); }
    public LocalDate previous(LocalDate value) { return value.minusDays(1); }
    public long distance(LocalDate start, LocalDate end) { return start.until(end, ChronoUnit.DAYS); }
    public LocalDate minValue() { return LocalDate.MIN; }
    public LocalDate maxValue() { return LocalDate.MAX; }
};

Set<LocalDate> datesInRange = ContiguousSet.create(Range.closed(d1, d2), localDateDomain);
M. Justin
  • 14,487
  • 7
  • 91
  • 130
1

In my time library Time4J, I have written an optimized spliterator to construct a stream of calendar dates with good parallelization characteristics. Adapted to your use-case:

LocalDate start = ...;
LocalDate end = ...;

Stream<LocalDate> stream = 
  DateInterval.between(start, end) // closed interval, else use .withOpenEnd()
    .streamDaily()
    .map(PlainDate::toTemporalAccessor);

This short approach can be an interesting start point if you are also interested in related features like clock intervals per calendar date (partitioned streams) or other interval features and want to avoid awkward hand-written code, see also the API of DateInterval.

Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126