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

前端 未结 8 1999
陌清茗
陌清茗 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 00:51

    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).

提交回复
热议问题