Java Joda Time - Implement a Date range iterator(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 - 实现日期范围迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java Joda Time - 实现日期范围迭代器
基础教程推荐
- 在螺旋中写一个字符串 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01