Joda 時間で日付イテレータを成功させずに実装しようとしています。
startDate から endDate までのすべての日を反復できるものが必要です。それ
を行う方法について何か考えはありますか?
11985 次
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
于 2010-06-24T09:29:15.420 に答える