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

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

    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 {
    
      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 iterator() {
        return stream().iterator();
      }
    
      public Stream stream() {
        return Stream.iterate(startDate, d -> d.plusDays(1))
                     .limit(ChronoUnit.DAYS.between(startDate, endDate) + 1);
      }
    
      public List toList() { //could also be built from the stream() method
        List 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.

提交回复
热议问题