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

查看:684
本文介绍了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());
}

现在我需要 startDate endDate

我在想把 code>两个日期并迭代:

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天全站免登陆