如何在java中获取两个日期之间的日期列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2689379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:52:07  来源:igfitidea点击:

how to get a list of dates between two dates in java

javadate

提问by Arivu2020

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.

结果应该是所有日期的列表,包括开始和结束日期。

回答by folone

One solution would be to create a Calendarinstance, and start a cycle, increasing it's Calendar.DATEfield until it reaches the desired date. Also, on each step you should create a Dateinstance (with corresponding parameters), and put it to your list.

一种解决方案是创建一个Calendar实例,然后开始一个循环,增加它的Calendar.DATE字段直到到达所需的日期。此外,在每个步骤中,您都应该创建一个Date实例(带有相应的参数),并将其放入您的列表中。

Some dirty code:

一些脏代码:

    public List<Date> getDatesBetween(final Date date1, final Date date2) {
    List<Date> dates = new ArrayList<Date>();

    Calendar calendar = new GregorianCalendar() {{
        set(Calendar.YEAR, date1.getYear());
        set(Calendar.MONTH, date1.getMonth());
        set(Calendar.DATE, date1.getDate());
    }};

    while (calendar.get(Calendar.YEAR) != date2.getYear() && calendar.get(Calendar.MONTH) != date2.getMonth() && calendar.get(Calendar.DATE) != date2.getDate()) {
        calendar.add(Calendar.DATE, 1);
        dates.add(new Date(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE)));
    }

    return dates;
}

回答by extraneon

You can also look at the Date.getTime()API. That gives a long to which you can add your increment. Then create a new Date.

您还可以查看Date.getTime()API。这给出了一个可以添加增量的 long 。然后创建一个新的日期。

List<Date> dates = new ArrayList<Date>();
long interval = 1000 * 60 * 60; // 1 hour in millis
long endtime = ; // create your endtime here, possibly using Calendar or Date
long curTime = startDate.getTime();
while (curTime <= endTime) {
  dates.add(new Date(curTime));
  curTime += interval;
}

and maybe apache commons has something like this in DateUtils, or perhaps they have a CalendarUtils too :)

也许 apache commons 在 DateUtils 中有这样的东西,或者他们也有一个 CalendarUtils :)

EDIT

编辑

including the start andenddate may not be possible if your interval is not perfect :)

如果您的时间间隔不完美,则可能无法包括开始和结束日期:)

回答by Albert

Back in 2010, I suggested to use Joda-Timefor that.

Note that Joda-Time is now in maintenance mode. Since 1.8 (2014), you should use java.time.

早在 2010 年,我建议为此使用Joda-Time

请注意,Joda-Time 现在处于维护模式。从 1.8 (2014) 开始,您应该使用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.

实现自己的迭代器也不会太难,那会更好。

回答by Jules Rogerson

Get the number of days between dates, inclusive.

获取日期之间的天数,包括在内。

public 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;
}

回答by bidyot

please find the below code.

请找到以下代码。

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);
}

output:

输出:

Date is ...27/08/2010
Date is ...28/08/2010
Date is ...29/08/2010
Date is ...30/08/2010
Date is ...31/08/2010
Date is ...01/09/2010
Date is ...02/09/2010

日期是 ...27/08/2010
日期是 ...28/08/2010
日期是 ...29/08/2010
日期是 ...30/08/2010
日期是 ...31/08/2010
日期是 ...01/09/2010
日期是 ...02/09/2010

回答by mfruizs2

With Joda-Time, maybe it's better:

使用Joda-Time,也许更好:

LocalDate dateStart = new LocalDate("2012-01-15");
LocalDate dateEnd = new LocalDate("2012-05-23");
// day by day:
while(dateStart.isBefore(dateEnd)){
    System.out.println(dateStart);
    dateStart = dateStart.plusDays(1);
}

It's my solution.... very easy :)

这是我的解决方案......非常简单:)

回答by Upendra

List<Date> dates = new ArrayList<Date>();
String str_date = "DD/MM/YYYY";
String end_date = "DD/MM/YYYY";
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date startDate = (Date)formatter.parse(str_date); 
Date endDate = (Date)formatter.parse(end_date);
long interval = 1000 * 60 * 60; // 1 hour in milliseconds
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);
    //Write your code for storing dates to list
}

回答by Krzysztof Szewczyk

Like as @folone, but correct

就像@folone,但正确

private static List<Date> getDatesBetween(final Date date1, final Date date2) {
    List<Date> dates = new ArrayList<>();
    Calendar c1 = new GregorianCalendar();
    c1.setTime(date1);
    Calendar c2 = new GregorianCalendar();
    c2.setTime(date2);
    int a = c1.get(Calendar.DATE);
    int b = c2.get(Calendar.DATE);
    while ((c1.get(Calendar.YEAR) != c2.get(Calendar.YEAR)) || (c1.get(Calendar.MONTH) != c2.get(Calendar.MONTH)) || (c1.get(Calendar.DATE) != c2.get(Calendar.DATE))) {
        c1.add(Calendar.DATE, 1);
        dates.add(new Date(c1.getTimeInMillis()));
    }
    return dates;
}

回答by Alex Semeniuk

Something like this should definitely work:

像这样的事情绝对应该有效:

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;
}

回答by Yadu Krishnan

java.time Package

java.time 包

If you are using Java 8, there is a much cleaner approach. The new java.time packagein Java 8 incorporates the features of the Joda-TimeAPI.

如果您使用的是Java 8,则有一种更简洁的方法。Java 8 中新的java.time 包结合了Joda-TimeAPI 的特性。

Your requirement can be solved using the below code:

可以使用以下代码解决您的要求:

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);
}