本文介紹了Java Joda Time - 實現日期范圍迭代器的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在嘗試使用 Joda 時間實現 Date 迭代器,但沒有成功.
我需要一些東西來讓我從 startDate 到 endDate
你知道怎么做嗎?
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 have any idea on how to do that?
推薦答案
這里有一些東西可以幫助您入門.您可能需要考慮是否希望它最終具有包容性或排他性等.
Here's something to get you started. You may want to think about whether you want it to be inclusive or exclusive at the end, etc.
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 編寫迭代器了,所以我希望它是對的.我覺得還可以...
It's a while since I've written an iterator in Java, so I hope it's right. I think it's pretty much okay...
哦,對于 C# 迭代器塊,我只能這么說......
Oh for C# iterator blocks, that's all I can say...
這篇關于Java Joda Time - 實現日期范圍迭代器的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!