你可以这样做:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Tests
System.out.println(getDateList("20200101", "20200110"));
System.out.println(getDateList("20200101", "20200131"));
}
static List<String> getDateList(String strStartDate, String strEndDate) {
// List to be populated with the desired strings
List<String> result = new ArrayList<>();
// Formatter for the desired pattern
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
// Parse strings to LocalDate instances
LocalDate startDate = LocalDate.parse(strStartDate, formatter);
LocalDate endDate = LocalDate.parse(strEndDate, formatter);
// Loop starting with start date until end date with a step of one day
for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
result.add(date.format(formatter));
}
// Return the populated list
return result;
}
}
输出:
[20200101, 20200102, 20200103,..., 20200110]
[20200101, 20200102, 20200103,..., 20200131]
使用 Java Stream API 的解决方案:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
// Tests
System.out.println(getDateList("20200101", "20200110"));
System.out.println(getDateList("20200101", "20200131"));
}
static List<String> getDateList(String strStartDate, String strEndDate) {
// Formatter for the input and desired pattern
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
// Parse strings to LocalDate instances
LocalDate startDate = LocalDate.parse(strStartDate, formatter);
LocalDate endDate = LocalDate.parse(strEndDate, formatter);
return Stream.iterate(startDate, date -> date.plusDays(1))
.limit(ChronoUnit.DAYS.between(startDate, endDate.plusDays(1)))
.map(date -> date.format(formatter))
.collect(Collectors.toList());
}
}