Java 8 LocalDate - 如何获取两个日期之间的所有日期?

2022-08-31 15:15:12

是否可以在新 API 中获取两个日期之间的所有日期java.time

假设我有这部分代码:

@Test
public void testGenerateChartCalendarData() {
    LocalDate startDate = LocalDate.now();

    LocalDate endDate = startDate.plusMonths(1);
    endDate = endDate.withDayOfMonth(endDate.lengthOfMonth());
}

现在我需要 和 之间的所有日期。startDateendDate

我正在考虑获取两个日期并迭代:daysBetween

long daysBetween = ChronoUnit.DAYS.between(startDate, endDate);

for(int i = 0; i <= daysBetween; i++){
    startDate.plusDays(i); //...do the stuff with the new date...
}

有没有更好的方法来获取日期?


答案 1

假设您主要想迭代日期范围,那么创建一个可迭代的类是有意义的。这将允许您编写:DateRange

for (LocalDate d : DateRange.between(startDate, endDate)) ...

像这样:

public class DateRange implements Iterable<LocalDate> {

  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<LocalDate> iterator() {
    return stream().iterator();
  }

  public Stream<LocalDate> stream() {
    return Stream.iterate(startDate, d -> d.plusDays(1))
                 .limit(ChronoUnit.DAYS.between(startDate, endDate) + 1);
  }

  public List<LocalDate> toList() { //could also be built from the stream() method
    List<LocalDate> dates = new ArrayList<> ();
    for (LocalDate d = startDate; !d.isAfter(endDate); d = d.plusDays(1)) {
      dates.add(d);
    }
    return dates;
  }
}

添加 equals & hashcode 方法、getters,也许有一个静态工厂 + 私有构造函数来匹配 Java 时间 API 的编码风格等是有意义的。


答案 2

首先,您可以使用 a 获取该月的最后一天。接下来,API提供Stream::iterate,这是解决您问题的正确工具。TemporalAdjusterStream

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