Java Joda Time - Implement a Date range iterator

前端 未结 3 1150
无人共我
无人共我 2020-12-05 20:19

I\'m trying to implement without success a Date iterator with Joda time.
I need something that allows me to iterate all the days form startDate to endDate
Do you h

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-05 21:17

    I know you asked about Joda-Time. Today we should prefer to use java.time, the modern Java date and time API that is basically a further development of Joda-Time. Since Java 9 the iteration of a date range has been built in through a Stream:

        LocalDate startDate = LocalDate.of(2019, Month.AUGUST, 28);
        LocalDate endate = LocalDate.of(2019, Month.SEPTEMBER, 3);
        startDate.datesUntil(endate).forEach(System.out::println);
    

    Output:

    2019-08-28
    2019-08-29
    2019-08-30
    2019-08-31
    2019-09-01
    2019-09-02
    

    If you wanted the end date to be inclusive, use datesUntil(endate.plusDays(1)).

    And if you literally wanted an Iterator:

        Iterator ldi = startDate.datesUntil(endate).iterator();
    

    The Joda-Time home page says:

    Note that Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to java.time (JSR-310).

    (Joda-Time - Home)

提交回复
热议问题