简体   繁体   English

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

[英]Java: How to iterate over days in a Period object

If I have a Period object defined like this: 如果我有一个像这样定义的Period对象:

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

how to iterate over all days starting from first day until the last one? 如何迭代从第一天到最后一天的所有日子? I need a loop that has an object LocalDate referring to the current date to process it. 我需要一个循环,它有一个对象LocalDate引用当前日期来处理它。

As Jon Skeet explained, you cannot do this with java.time.Period . 正如Jon Skeet解释的那样,你无法用java.time.Period做到这java.time.Period It is simply not an interval. 这根本不是间隔。 There is no anchor on the date line. 日期线上没有锚点。 But you have start and end, so this is possible: 但是你有开始和结束,所以这是可能的:

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

Output: 输出:

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

You can't - because a Period doesn't know its start/end dates... it only knows how long it is in terms of years, months, days etc. In that respect, it's a sort of calendar-centric version of Duration . 你不能 - 因为一个Period不知道它的开始/结束日期...... 它只知道它在几年,几个月,几天等方面有多长。在这方面,它是一种以日历为中心的版本Duration

If you want to create your own, it would be easy to do, of course - but I don't believe there's anything out of the box in either java.time (or Joda Time, as it happens) to do this. 如果你想创建自己的,当然很容易做到 - 但是我不相信java.time (或者Joda Time,就像它发生的那样)开箱即java.time

There is a new way in Java 9. You can obtain Stream<LocalDate> of days between start and end. 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 . 你可以在这里阅读更多

Even though Jon Skeet's answer is the right answer, an easy workaround would be 尽管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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM