Java Joda Time - Implementar un iterador intervalo de fechas
Pregunta
Estoy tratando de poner en práctica sin éxito un iterador de fecha con el tiempo Joda.
Necesito algo que me permite iterar todo el día forma startDate a endDate
¿Tiene alguna idea de cómo hacer eso?
Solución
Aquí hay algo para empezar. Es posible que desee pensar en si usted quiere que sea inclusivo o exclusivo al final, 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);
}
}
}
Es un tiempo desde que he escrito un iterador en Java, por lo que esperanza que es correcto. Creo que es más o menos bien ...
Oh para C # bloques de iterador, eso es todo lo que puedo decir ...
Otros consejos
Sé que preguntará sobre Joda-Time. Hoy deberíamos preferir utilizar java.time, la fecha moderna Java y API de tiempo que es básicamente un desarrollo adicional de Joda-Time. Desde Java 9 de la iteración de un intervalo de fechas se ha construido a través de una Stream
:
LocalDate startDate = LocalDate.of(2019, Month.AUGUST, 28);
LocalDate endate = LocalDate.of(2019, Month.SEPTEMBER, 3);
startDate.datesUntil(endate).forEach(System.out::println);
Salida:
2019-08-28 2019-08-29 2019-08-30 2019-08-31 2019-09-01 2019-09-02
Si quieres la fecha final que sea incluyente, el uso datesUntil(endate.plusDays(1))
.
Y si usted quiere, literalmente, un Iterator
:
Iterator<LocalDate> ldi = startDate.datesUntil(endate).iterator();
La página principal Joda-Time dice:
Tenga en cuenta que Joda-Time se considera que es un proyecto en gran medida “terminado”. No se han previsto importantes mejoras. Si se utiliza Java SE 8, por favor migrar a
java.time
(JSR-310).