java.time through desugaring
Consider using java.time, the modern Java date and time API, for your date work. LocalDate
is the class to use for a date (without time of day). I was assuming you wanted all the dates inclusive of the two given ones.
String first = "2012-07-15";
String second = "2012-07-21";
List<LocalDate> dates = LocalDate.parse(first)
.datesUntil(LocalDate.parse(second).plusDays(1))
.collect(Collectors.toList());
System.out.println(dates);
Output:
[2012-07-15, 2012-07-16, 2012-07-17, 2012-07-18, 2012-07-19,
2012-07-20, 2012-07-21]
LocalDate.datesUntil()
gives us a stream of dates exclusive of the specified end date, so we need to add one day to it to have it included.
I am exploiting the fact that your strings are in ISO 8601 format and that LocalDate
parses this format as its default, that is, without any explicit formatter.
Or through ThreeTenABP
If for some reason you are using the ThreeTenABP library rather than desugaring, I believe that the datesUntil
method is not there. In this case use a loop instead.
List<LocalDate> dates = new ArrayList<>();
LocalDate currentDate = LocalDate.parse(first);
LocalDate lastDate = LocalDate.parse(second);
while (! currentDate.isAfter(lastDate )) {
dates.add(currentDate);
currentDate = currentDate.plusDays(1);
}
[2012-07-15, 2012-07-16, 2012-07-17, 2012-07-18, 2012-07-19,
2012-07-20, 2012-07-21]
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
- In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
- In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
- On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links