12

我试图用 Joda 时间实现一个 Date 迭代器,但没有成功。
我需要一些可以让我从 startDate 到 endDate 的所有日子迭代的东西
你对如何做到这一点有任何想法吗?

4

3 回答 3

28

这里有一些东西可以帮助您入门。您可能要考虑是否希望它最终具有包容性或排他性等。

import org.joda.time.*;
import java.util.*;

class LocalDateRange implements Iterable<LocalDate>
{
    private final LocalDate start;
    private final LocalDate end;

    public LocalDateRange(LocalDate start,
                          LocalDate end)
    {
        this.start = start;
        this.end = end;
    }

    public Iterator<LocalDate> iterator()
    {
        return new LocalDateRangeIterator(start, end);
    }

    private static class LocalDateRangeIterator implements Iterator<LocalDate>
    {
        private LocalDate current;
        private final LocalDate end;

        private LocalDateRangeIterator(LocalDate start,
                                       LocalDate end)
        {
            this.current = start;
            this.end = end;
        }

        public boolean hasNext()
        {
            return current != null;
        }

        public LocalDate next()
        {
            if (current == null)
            {
                throw new NoSuchElementException();
            }
            LocalDate ret = current;
            current = current.plusDays(1);
            if (current.compareTo(end) > 0)
            {
                current = null;
            }
            return ret;
        }

        public void remove()
        {
            throw new UnsupportedOperationException();
        }
    }
}

class Test
{
    public static void main(String args[])
    {
        LocalDate start = new LocalDate(2009, 7, 20);
        LocalDate end = new LocalDate(2009, 8, 3);
        for (LocalDate date : new LocalDateRange(start, end))
        {
            System.out.println(date);
        }
    }
}

自从我用 Java 编写迭代器以来已经有一段时间了,所以我希望它是正确的。我觉得还不错。。。

哦,对于 C# 迭代器块,我只能这么说......

于 2009-07-23T23:54:16.907 回答
1

http://code.google.com/p/google-rfc-2445

于 2010-06-24T09:29:15.420 回答
1

我知道你问过 Joda-Time。今天我们应该更喜欢使用 java.time,这是现代 Java 日期和时间 API,它基本上是 Joda-Time 的进一步发展。自 Java 9 以来,日期范围的迭代已通过以下方式内置Stream

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

输出:

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

如果您希望结束日期包含在内,请使用datesUntil(endate.plusDays(1)).

如果你真的想要一个Iterator

    Iterator<LocalDate> ldi = startDate.datesUntil(endate).iterator();

Joda-Time 主页说:

请注意,Joda-Time 被认为是一个基本上“完成”的项目。没有计划进行重大改进。如果使用 Java SE 8,请迁移到java.time(JSR-310)。

( Joda-Time - 主页)

于 2019-09-04T13:34:27.933 回答