How to get list of dates between two dates?
android, java, jodatime
Solution
For a list you could just do:
public static List<LocalDate> datesBetween(LocalDate start, LocalDate end) {
List<LocalDate> ret = new ArrayList<LocalDate>();
for (LocalDate date = start; !date.isAfter(end); date = date.plusDays(1)) {
ret.add(date);
}
return ret;
}
Note, that will include `end`. If you want it to exclude the end, just change the condition in the loop to `date.isBefore(end)`.
If you only need an `Iterable<LocalDate>` you could write your own class to do this very efficiently rather than building up a list. You could do this with an anonymous class, if you didn't mind a fair degree of nesting. For example (untested):
public static Iterable<LocalDate> datesBetween(final LocalDate start,
final LocalDate end) {
return new Iterable<LocalDate>() {
@Override public Iterator<LocalDate> iterator() {
return new Iterator<LocalDate>() {
private LocalDate next = start;
@Override
public boolean hasNext() {
return !next.isAfter(end);
}
@Override
public LocalDate next() {
if (next.isAfter(end)) {
throw NoSuchElementException();
}
LocalDate ret = next;
next = next.plusDays(1);
return ret;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
Problem
In my application user should select date from `listview`. The problem is generating this list. For example I need all dates between 2010-2013 or June-August (period maybe day, month, year). Is there any method that allows to get that data? Example: I need dates between 01.01.2013 - 10.01.2013 - 01.01.2013 - 02.01.2013 - 03.01.2013 - 04.01.2013 - 05.01.2013 - 06.01.2013 - 07.01.2013 - 08.01.2013 - 09.01.2013 - 10.01.2013 Thanks in advance