如何在java中获取两个日期之间的日期列表
问题描述:
我想要一个介于开始日期和结束日期之间的日期列表.
I want a list of dates between start date and end date.
结果应该是所有日期的列表,包括开始和结束日期.
The result should be a list of all dates including the start and end date.
答
早在 2010 年,我就建议为此使用 Joda-Time.
请注意,Joda-Time 现在处于维护模式.从 1.8 (2014) 开始,您应该使用 java.time
.
Note that Joda-Time is now in maintenance mode. Since 1.8 (2014), you should use java.time
.
一次添加一天,直到到达结束日期:
Add one day at a time until reaching the end date:
int days = Days.daysBetween(startDate, endDate).getDays();
List<LocalDate> dates = new ArrayList<LocalDate>(days); // Set initial capacity to `days`.
for (int i=0; i < days; i++) {
LocalDate d = startDate.withFieldAdded(DurationFieldType.days(), i);
dates.add(d);
}
实现自己的迭代器也不会太难,那样会更好.
It wouldn't be too hard to implement your own iterator to do this as well, that would be even nicer.