Java 8 LocalDate-如何获取两个日期之间的所有日期?
在新API中是否有可能获取 java.time
?
假设我有这部分代码:
@Testpublic void testGenerateChartCalendarData() {
LocalDate startDate = LocalDate.now();
LocalDate endDate = startDate.plusMonths(1);
endDate = endDate.withDayOfMonth(endDate.lengthOfMonth());
}
现在我需要介于startDate
和之间的所有日期endDate
。
我正在考虑获取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...
}
有没有更好的方法来获取日期?
回答:
假设您主要想在日期范围内进行迭代,那么创建一个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方法,getter可能很有意义,也许有一个静态工厂+私有构造函数来匹配Java time API的编码样式等。
以上是 Java 8 LocalDate-如何获取两个日期之间的所有日期? 的全部内容, 来源链接: utcz.com/qa/419067.html