LiangYongrui's Studio.

得到两个日期内的全部日期

2018/10/11 Share

Java 7

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static List<Date> getDatesBetweenUsingJava7(Date startDate, Date endDate) {
List<Date> datesInRange = new ArrayList<>();
Calendar calendar = new GregorianCalendar();
calendar.setTime(startDate);

Calendar endCalendar = new GregorianCalendar();
endCalendar.setTime(endDate);

while (calendar.before(endCalendar)) {
Date result = calendar.getTime();
datesInRange.add(result);
calendar.add(Calendar.DATE, 1);
}
return datesInRange;
}

Java 8

1
2
3
4
5
6
7
public static List<LocalDate> getDatesBetweenUsingJava8(LocalDate startDate, LocalDate endDate) {
long numOfDaysBetween = ChronoUnit.DAYS.between(startDate, endDate);
return IntStream.iterate(0, i -> i + 1)
.limit(numOfDaysBetween)
.mapToObj(startDate::plusDays)
.collect(Collectors.toList());
}

Java 9

1
2
3
public static List<LocalDate> getDatesBetweenUsingJava9(LocalDate startDate, LocalDate endDate) {
return startDate.datesUntil(endDate).collect(Collectors.toList());
}
CATALOG
  1. 1. Java 7
  2. 2. Java 8
  3. 3. Java 9