Java 8 LocalDate - 如何获取两个日期之间的所有日期? [英] Java 8 LocalDate - How do I get all dates between two dates?

查看:284
本文介绍了Java 8 LocalDate - 如何获取两个日期之间的所有日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a usablility to get all dates between two dates in the new java.time API?

假设我有这部分代码:

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

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

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

Now I need all dates between startDate and endDate.

我想获取两个日期的 daysBetween 并迭代:

I was thinking to get the daysBetween of the two dates and iterate over:

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

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

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

Is there a better way to get the dates?

推荐答案

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

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

类似于:

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 方法,getter,也许有一个静态工厂 + 私有构造函数来匹配 Java 时间 API 等的编码风格.

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.

这篇关于Java 8 LocalDate - 如何获取两个日期之间的所有日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆