- 我需要一个包括起始日期和结束日期在内的日期列表。
- 结果应该是一个包含所有日期的列表,包括起始日期和结束日期。
如果您正在使用Java 8,那么有一种更加简洁的方法。Java 8中的新java.time包包含了Joda-Time API的功能。
您可以使用以下代码来满足您的需求:
String s = "2014-05-01";
String e = "2014-05-10";
LocalDate start = LocalDate.parse(s);
LocalDate end = LocalDate.parse(e);
List<LocalDate> totalDates = new ArrayList<>();
while (!start.isAfter(end)) {
totalDates.add(start);
start = start.plusDays(1);
}
ArrayList
构造函数来设置列表的初始容量。 int initialCapacity = java.lang.Math.toIntExact( ChronoUnit.DAYS.between( start , end ) ) ;
- Basil BourqueStream<LocalDate>
使得使用LocalDate
更加容易,从而消除了构建自己的while
循环的需要。请参阅Hochschild的答案。 - Basil Bourque2010年,我建议使用Joda-Time。
请注意,Joda-Time现在处于维护模式。自1.8(2014年)以来,您应该使用
java.time
。
逐天添加一天,直到达到结束日期:
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);
}
你自己编写一个迭代器来实现这个功能也并不难,而且会更好。
plusDays
函数来简化该代码。因此,将LocalDate d = startDate.withFieldAdded(DurationFieldType.days(), i);
改为LocalDate d = startDate.plusDays(i);
。 - Basil Bourquepublic static List<Date> getDaysBetweenDates(Date startdate, Date enddate)
{
List<Date> dates = new ArrayList<Date>();
Calendar calendar = new GregorianCalendar();
calendar.setTime(startdate);
while (calendar.getTime().before(enddate))
{
Date result = calendar.getTime();
dates.add(result);
calendar.add(Calendar.DATE, 1);
}
return dates;
}
before()
方法(相当于<操作符)时,最终列表将不包括“fechaFinal”(结束日期)。应该使用<=操作符。由于Calendar
类中没有相应的方法,因此应适当增加结束日期。 - Alex Semeniukwhile (calendar.getTime().getTime() <= enddate.getTime())
- Ricardo Teixeirajava.util.Date
、java.util.Calendar
和java.text.SimpleDateFormat
这样的老旧日期时间类现在已经成为遗留系统,被内置于Java 8及更高版本中的java.time类所取代。请参阅Oracle的教程。 - Basil Bourque编辑:Joda-Time现已过时,将答案更改为使用Java 8。
以下是使用流(streams)的Java 8方法。
List<LocalDate> daysRange = Stream.iterate(startDate, date -> date.plusDays(1)).limit(numOfDays).collect(Collectors.toList());
请查看以下代码:
List<Date> dates = new ArrayList<Date>();
String str_date ="27/08/2010";
String end_date ="02/09/2010";
DateFormat formatter ;
formatter = new SimpleDateFormat("dd/MM/yyyy");
Date startDate = (Date)formatter.parse(str_date);
Date endDate = (Date)formatter.parse(end_date);
long interval = 24*1000 * 60 * 60; // 1 hour in millis
long endTime =endDate.getTime() ; // create your endtime here, possibly using Calendar or Date
long curTime = startDate.getTime();
while (curTime <= endTime) {
dates.add(new Date(curTime));
curTime += interval;
}
for(int i=0;i<dates.size();i++){
Date lDate =(Date)dates.get(i);
String ds = formatter.format(lDate);
System.out.println(" Date is ..." + ds);
}
输出:
日期为...27/08/2010
日期为...28/08/2010
日期为...29/08/2010
日期为...30/08/2010
日期为...31/08/2010
日期为...01/09/2010
日期为...02/09/2010
在 Java 9 中,您可以使用以下新方法:LocalDate::datesUntil
:
LocalDate start = LocalDate.of(2017, 2, 1);
LocalDate end = LocalDate.of(2017, 2, 28);
Stream<LocalDate> dates = start.datesUntil(end.plusDays(1));
List<LocalDate> list = dates.collect(Collectors.toList());
新方法datesUntil(...)
使用独占结束日期,因此需要使用显示处理来添加一天。java.util.stream
或java.util.function
包提供的所有功能。与基于自定义for-或while循环的早期方法相比,使用流的工作变得非常简单。PlainDate start = PlainDate.of(2017, 2, 1);
PlainDate end = start.with(PlainDate.DAY_OF_MONTH.maximized());
Stream<PlainDate> stream = DateInterval.streamDaily(start, end);
对于整月来说,甚至更简单:
Stream<PlainDate> februaryDates = CalendarMonth.of(2017, 2).streamDaily();
List<LocalDate> list =
februaryDates.map(PlainDate::toTemporalAccessor).collect(Collectors.toList());
使用Java 8
public Stream<LocalDate> getDaysBetween(LocalDate startDate, LocalDate endDate) {
return IntStream.range(0, (int) DAYS.between(startDate, endDate)).mapToObj(startDate::plusDays);
}
类似这样的代码一定可以运行:
private List<Date> getListOfDaysBetweenTwoDates(Date startDate, Date endDate) {
List<Date> result = new ArrayList<Date>();
Calendar start = Calendar.getInstance();
start.setTime(startDate);
Calendar end = Calendar.getInstance();
end.setTime(endDate);
end.add(Calendar.DAY_OF_YEAR, 1); //Add 1 day to endDate to make sure endDate is included into the final list
while (start.before(end)) {
result.add(start.getTime());
start.add(Calendar.DAY_OF_YEAR, 1);
}
return result;
}
public static List<Date> getDaysBetweenDates(Date startDate, Date endDate){
ArrayList<Date> dates = new ArrayList<Date>();
Calendar cal1 = Calendar.getInstance();
cal1.setTime(startDate);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(endDate);
while(cal1.before(cal2) || cal1.equals(cal2))
{
dates.add(cal1.getTime());
cal1.add(Calendar.DATE, 1);
}
return dates;
}
使用 Lamma,在Java中可以这样写:
for (Date d: Dates.from(2014, 6, 29).to(2014, 7, 1).build()) {
System.out.println(d);
}
输出结果为:
Date(2014,6,29)
Date(2014,6,30)
Date(2014,7,1)
(fromDate..toDate).each { println it }
- lepe