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

前端 未结 8 1978
陌清茗
陌清茗 2020-12-03 00:10

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:



        
相关标签:
8条回答
  • 2020-12-03 01:07

    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());
    
    0 讨论(0)
  • 2020-12-03 01:11

    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);
    
    0 讨论(0)
提交回复
热议问题