Parse each string into a LocalDate
object using a DateTimeFormatter
. Search for how (if your search leads to a page using the old and troublesome SimpleDateFormat
, avoid that). Create two variables for the start and end of the current interval. Store the first date into both. In a loop over the remaining dates:
- If the current date is one day after the end, store it into the end, thus extending the interval by one day.
- Otherwise print the current interval, see below for how. Then again store the current date into both start and end.
After the loop terminates, print the current interval.
How to print the current interval: if start and end are equal, print only one of them; otherwise print both with an en-dash between them. In either case format each printed date into the desired format, for example the original format using the same DateTimeFormatter
.
To determine whether current date is one day after end, use the plusDays
and the isEqual
methods of LocalDate
.
Question: Doesn’t LocalDate
require Android API level 26?
LocalDate
is part of java.time, the modern Java date and time API. 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