从两个日期/时间戳创建日期范围?

时间:2015-06-30 22:00:28

标签: java date

如果知道两个结束日期,如何获得一系列日期?

即。如果我希望所有日期都在2015-06-07 00:00:002015-01-01 00:00:00之间,那么如果两个日期都已在DateTimestamp个对象中生成,我该怎么办呢?

我知道在Python中可以使用datetime模块:

[str(end_date + timedelta(days=x)) for x in range((start_date-end_date).days + 1)]

Java中的等价物是什么?

2 个答案:

答案 0 :(得分:2)

使用Joda:

LocalDate from = new LocalDate(fromDate);
LocalDate to = new LocalDate(toDate);
int nDays = Days.daysBetween(from, to).getDays();

List<Date> days = new ArrayList<>(nDays);
for(int i = 0 ; i <= nDays ; i++) {
    days.add(from.plusDays(i).toDate());
}

或者在Java 8中:

final LocalDate from = new LocalDate(fromDate);
final LocalDate to = new LocalDate(toDate);
List<Date> days = IntStream.range(0, Days.daysBetween(from, to).getDays() + 1)
                           .map(i -> from.plusDays(i).toDate())
                           .collect(Collectors.toList());

答案 1 :(得分:1)

java.util.Calendar方法:

Calendar start = Calendar.getInstance();
start.setTime(startDate);
Calendar end = Calendar.getInstance();
end.setTime(endDate);

for (Date date = start.getTime(); start.before(end); start.add(Calendar.DATE, 1), date = start.getTime()) {
    System.out.println(date);
}

java.time.LocalDate方法(需要Java 8):

LocalDate start = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate end = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

for (LocalDate date = start; date.isBefore(end); date = date.plusDays(1)) {
    System.out.println(date);
}