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

前端 未结 8 1975
陌清茗
陌清茗 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:02

    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 localDateDomain = new DiscreteDomain() {
        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 datesInRange = ContiguousSet.create(Range.closed(d1, d2), localDateDomain);
    

提交回复
热议问题