Java:如何在Period对象中迭代几天

时间:2016-02-29 11:43:00

标签: java

如果我有一个像这样定义的Period对象:

Period.between(LocalDate.of(2015,8,1), LocalDate.of(2015,9,2))

如何迭代从第一天到最后一天的所有日子?我需要一个具有对象LocalDate的循环,引用当前日期来处理它。

4 个答案:

答案 0 :(得分:4)

正如Jon Skeet解释的那样,你不能用java.time.Period做到这一点。这根本不是间隔。日期线上没有锚点。但是你有开始和结束,所以这是可能的:

LocalDate start = LocalDate.of(2015, 8, 1);
LocalDate end = LocalDate.of(2015, 9, 2);
Stream<LocalDate> stream = 
    LongStream
        .range(start.toEpochDay(), end.toEpochDay() + 1) // end interpreted as inclusive
        .mapToObj(LocalDate::ofEpochDay);
stream.forEach(System.out::println);

输出:

2015-08-01
2015-08-02
2015-08-03
...
2015-08-31
2015-09-01
2015-09-02

答案 1 :(得分:2)

你不能 - 因为Period并不知道它的开始/结束日期......只有 知道它的年数,几个月,几天等。在这方面,它是Duration的一种以日历为中心的版本。

如果你想创造自己的,当然很容易做到 - 但是我不相信java.time(或者Joda Time)中有任何开箱即用的东西,正好这样做。

答案 2 :(得分:2)

Java 9中有一种新方法。您可以在开始和结束之间获得Stream<LocalDate>天。

start
  .datesUntil(end)
  .forEach(it -> out.print(“ > “ + it));
--
> 2017–04–14 > 2017–04–15 > 2017–04–16 > 2017–04–17 > 2017–04–18 > 2017–04–19

You can read more here

答案 3 :(得分:1)

尽管Jon Skeet的回答是正确的答案,但一个简单的解决方法就是

LocalDate currentStart=LocalDate.from(start);
LocalDate currentEnd=LocalDate.from(end.plusDays(1));//end is inclusive
do{
    // do what you want with currentStart
    //....
    currentStart=currentStart.plusDays(1);
}while (!currentStart.equals(currentEnd));