本文介绍了Java日期迭代器工厂,具有规定如何计算间隔的规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个Java类,在那里我可以指定一组日期规则,例如每3个星期日和每隔一个星期一的第一次出现。我想要能够得到类似无限迭代器的东西(.next()将返回匹配规则集的下一个日期)。

I am looking for a Java class where I can specify a set of date rules, such as "every 3rd sunday" and "the first occurrence of a monday every second month". I want to be able to get something like an infinite iterator out of it (.next() would return the next date matching the rules set).

我想我'能够自己建立 - 但日历是一件麻烦,感觉就像已经存在的东西一样。我讨厌成为一个重新开发一个crappier轮。

I think I'd be able to build it myself - but calendars are a hassle, and it feels like something similar should exist already. I hate being the one to reinvent a crappier wheel.

有人知道这样的事情吗?我一直在看JODA,它似乎为此打下了基础,但似乎没有给出我想要的全部功能。

Is anyone aware of something like this? I have been looking at JODA, and it seems to lay the groundwork for it, but does not appear to give the full functionality I want..

推荐答案

我认为没有任何容易的迭代器用于joda-time或Java Calendar API,但是对于joda来说,这么简单就可以了。例如,在几个月后,我重新熟悉自己,我在大约10分钟内完成了这个工作:

I don't think there's any readily made iterators for joda-time or Java Calendar API for that matter, however with joda it's so easy that you should just go with it. For example after re-familiarizing myself with joda after a few months pause I made this in about 10 minutes:

public class InstantIterator implements Iterator<Instant>,
                                        Iterable<Instant> {

    private Instant current;
    private final Instant original;
    private Duration skip;
    private List<Instant> skipThese;

    public InstantIterator(Instant startFrom, Duration skip) {
        this.current = original = startFrom;
        this.skip = skip;
        skipThese = new Vector<Instant>();
    }

    public boolean hasNext() {
        return true;
    }

    public Instant next() {
        Instant currentNext = current.toInstant();
        current = current.plus(skip);
        while (skipThese.contains(currentNext)) {
            currentNext = current.toInstant();
            current = current.plus(skip);
        }
        return currentNext;
    }

    public void remove() {
        skipThese.add(current.toInstant());
    }

    public Iterator<Instant> iterator() {
        return this;
    }

    public void rewind() {
        current = original.toInstant();
    }

    public void resetRemoved() {
        skipThese.clear();
    }

    public void resetIterator() {
        rewind();
        resetRemoved();
    }
}

Joda时间真棒: - )

Joda Time is awesome :-)

这篇关于Java日期迭代器工厂,具有规定如何计算间隔的规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 05:42