how to get a list of dates between two dates in java

后端 未结 22 1544
余生分开走
余生分开走 2020-11-22 13:24

I want a list of dates between start date and end date.

The result should be a list of all dates including the start and end date.

22条回答
  •  太阳男子
    2020-11-22 13:41

    Recommending date streams

    In Java 9, you can use following new method, LocalDate::datesUntil:

    LocalDate start = LocalDate.of(2017, 2, 1);
    LocalDate end = LocalDate.of(2017, 2, 28);
    
    Stream dates = start.datesUntil(end.plusDays(1));
    List list = dates.collect(Collectors.toList());
    

    The new method datesUntil(...) works with an exclusive end date, hence the shown hack to add a day.

    Once you have obtained a stream you can exploit all the features offered by java.util.stream- or java.util.function-packages. Working with streams has become so simple compared with earlier approaches based on customized for- or while-loops.


    Or if you look for a stream-based solution which operates on inclusive dates by default but can also be configured otherwise then you might find the class DateInterval in my library Time4J interesting because it offers a lot of special features around date streams including a performant spliterator which is faster than in Java-9:

    PlainDate start = PlainDate.of(2017,  2, 1);
    PlainDate end = start.with(PlainDate.DAY_OF_MONTH.maximized());
    Stream stream = DateInterval.streamDaily(start, end);
    

    Or even simpler in case of full months:

    Stream februaryDates = CalendarMonth.of(2017, 2).streamDaily();
    List list = 
        februaryDates.map(PlainDate::toTemporalAccessor).collect(Collectors.toList());
    

提交回复
热议问题