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

时间:2010-04-22 08:53:34

标签: java date

我想要一个开始日期和结束日期之间的日期列表。

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

21 个答案:

答案 0 :(得分:46)

  

早在2010年,我建议使用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);
}

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

答案 1 :(得分:38)

java.time包

如果您使用Java 8,则有一种更清洁的方法。 Java 8中的新java.time package包含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);
}

答案 2 :(得分:36)

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

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

答案 3 :(得分:18)

编辑:Joda-Time现已弃用,改为使用Java 8的答案。

这是使用流的Java 8方式。

List<LocalDate> daysRange = Stream.iterate(startDate, date -> date.plusDays(1)).limit(numOfDays).collect(Collectors.toList());

答案 4 :(得分:12)

请找到以下代码。

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
   日期是...... 2010年8月30日    日期是...... 31/08/2010
   日期是...... 01/09/2010
   日期是...... 02/09/2010

答案 5 :(得分:3)

推荐日期流

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循环的早期方法相比,使用流变得非常简单。

或者,如果您查找默认情况下在包含日期运行的基于流的解决方案,但也可以另外配置,那么您可能会发现我的库DateInterval中的类Time4J很有趣,因为它提供了日期流周围的许多特殊功能,包括一个比Java-9更快的高性能分裂器:

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

答案 6 :(得分:3)

这样的事情肯定有用:

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

答案 7 :(得分:3)

使用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)

答案 8 :(得分:2)

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

一些脏代码:

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

答案 9 :(得分:2)

使用java 8

public Stream<LocalDate> getDaysBetween(LocalDate startDate, LocalDate endDate) {
    return IntStream.range(0, (int) DAYS.between(startDate, endDate)).mapToObj(startDate::plusDays);
}

答案 10 :(得分:2)

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

答案 11 :(得分:1)

您还可以查看Date.getTime() API。这给你一个很长的时间来增加你的增量。然后创建一个新日期。

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

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

修改

如果你的间隔不完美,可能无法包括开始 enddate:)

答案 12 :(得分:1)

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

答案 13 :(得分:1)

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
}

答案 14 :(得分:1)

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

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

答案 15 :(得分:0)

增强上述解决方案之一。将结束日期添加1天有时会在结束日期之后再增加一天。


    public static List getDaysBetweenDates(Date startdate, Date enddate)
    {
        List dates = new ArrayList();
        Calendar startDay = new GregorianCalendar();
        calendar.setTime(startdate);
        Calendar endDay = new GregorianCalendar();
        endDay.setTime(enddate);
        endDay.add(Calendar.DAY_OF_YEAR, 1);
        endDay.set(Calendar.HOUR_OF_DAY, 0);
        endDay.set(Calendar.MINUTE, 0);
        endDay.set(Calendar.SECOND, 0);
        endDay.set(Calendar.MILLISECOND, 0);

        while (calendar.getTime().before(endDay.getTime())) {
            Date result = startDay.getTime();
            dates.add(result);
            startDay.add(Calendar.DATE, 1);
        }
        return dates;
    }

答案 16 :(得分:0)

这是我在两个日期之间获取日期的方法,包括/ w.o.包括工作日。它还将源和所需的日期格式作为参数。

public static List<String> getAllDatesBetweenTwoDates(String stdate,String enddate,String givenformat,String resultformat,boolean onlybunessdays) throws ParseException{
        DateFormat sdf;
        DateFormat sdf1;
        List<Date> dates = new ArrayList<Date>();
        List<String> dateList = new ArrayList<String>();
          SimpleDateFormat checkformat = new SimpleDateFormat(resultformat); 
          checkformat.applyPattern("EEE");  // to get Day of week
        try{
            sdf = new SimpleDateFormat(givenformat);
            sdf1 = new SimpleDateFormat(resultformat);
            stdate=sdf1.format(sdf.parse(stdate));
            enddate=sdf1.format(sdf.parse(enddate));

            Date  startDate = (Date)sdf1.parse( stdate); 
            Date  endDate = (Date)sdf1.parse( enddate);
            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 = sdf1.format(lDate);   
                if(onlybunessdays){
                    String day= checkformat.format(lDate); 
                    if(!day.equalsIgnoreCase("Sat") && !day.equalsIgnoreCase("Sun")){
                          dateList.add(ds);
                    }
                }else{
                      dateList.add(ds);
                }

                //System.out.println(" Date is ..." + ds);

            }


        }catch(ParseException e){
            e.printStackTrace();
            throw e;
        }finally{
            sdf=null;
            sdf1=null;
        }
        return dateList;
    }

方法调用就像:

public static void main(String aregs[]) throws Exception {
        System.out.println(getAllDatesBetweenTwoDates("2015/09/27","2015/10/05","yyyy/MM/dd","dd-MM-yyyy",false));
    }

您可以找到演示代码:Click Here

答案 17 :(得分:0)

尾递归版:

public static void datesBetweenRecursive(Date startDate, Date endDate, List<Date> dates) {
    if (startDate.before(endDate)) {
        dates.add(startDate);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        calendar.add(Calendar.DATE, 1);
        datesBetweenRecursive(calendar.getTime(), endDate, dates);
    }
}

答案 18 :(得分:0)

这是获取日期列表的简单解决方案

import java.io.*;
import java.util.*;
import java.text.SimpleDateFormat;  
public class DateList
{

public static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

 public static void main (String[] args) throws java.lang.Exception
 {

    Date dt = new Date();
    System.out.println(dt);

        List<Date> dates = getDates("2017-01-01",dateFormat.format(new Date()));
        //IF you don't want to reverse then remove Collections.reverse(dates);
         Collections.reverse(dates);
        System.out.println(dates.size());
    for(Date date:dates)
    {
        System.out.println(date);
    }
 }
 public static List<Date> getDates(String fromDate, String toDate)
 {
    ArrayList<Date> dates = new ArrayList<Date>();

    try {

        Calendar fromCal = Calendar.getInstance();
        fromCal.setTime(dateFormat .parse(fromDate));

        Calendar toCal = Calendar.getInstance();
        toCal.setTime(dateFormat .parse(toDate));

        while(!fromCal.after(toCal))
        {
            dates.add(fromCal.getTime());
            fromCal.add(Calendar.DATE, 1);
        }


    } catch (Exception e) {
        System.out.println(e);
    }
    return dates;
 }
}

答案 19 :(得分:0)

这将添加两个日期之间的所有日期,它将添加当前日期,然后将根据循环条件添加新日期。

private void onDateSet(){
    Calendar endDate = Calendar.getInstance(),startDate = Calendar.getInstance();
    startDate.set(currentYear,currentMonthOfYear,currentDayOfMonth);
    endDate.set(inputYear,inputMonthOfYear,inputDayOfMonth);
    datesToAdd(startDate,endDate);
    }

    //call for get dates list
    private List<Date> datesToAdd(Calendar startDate,Calendar endDate){
                    List<Dates> datesLists = new List<>();
                    while (startDate.get(Calendar.YEAR) != endDate.get(Calendar.YEAR) ||   
                           startDate.get(Calendar.MONTH) != endDate.get(Calendar.MONTH) ||
                           startDate.get(Calendar.DAY_OF_MONTH) != endDate.get(Calendar.DAY_OF_MONTH)) {

                             datesList.add(new Date(startDate.get(Calendar.YEAR), startDate.get(Calendar.MONTH), startDate.get(Calendar.DATE));

                             startDate.add(Calendar.DATE, 1);//increas dates

                         }
                         return datesList;
                }

答案 20 :(得分:-1)

  您可以像这样计算

java9功能

public  List<LocalDate> getDatesBetween (
 LocalDate startDate, LocalDate endDate) {

   return startDate.datesUntil(endDate)
     .collect(Collectors.toList());
}
``