如何获得java中两个date之间的date列表

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

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

我build议使用Joda-Time 。 一次添加一天,直到到达结束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); } 

实现你自己的迭代器也不难,甚至更好。

获取date之间的天数(包括date)。

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

java.time包

如果您正在使用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); } 

stream

这是Java 8的方式,使用stream和Joda-Time 。

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

您可以使用Java 8和更高版本中的java.time框架来使用LocalDate类。

请find下面的代码。

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

输出:

date是… 27/08/2010
date是… 28/08/2010
date是… 29/08/2010
date是… 30/08/2010
date是… 31/08/2010
date是… 01/09/2010
date是… 02/09/2010

像这样的东西肯定会工作:

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

有了南丫岛,它在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) 

一种解决scheme是创build一个Calendar实例,并启动一个循环,增加它的Calendar.DATE字段,直到它达到所需的date。 另外,在每一步你都应该创build一个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; } 

你也可以看看Date.getTime() API。 这给你一个很长的时间,你可以添加你的增量。 然后创build一个新的date。

 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的公共在DateUtils中有这样的事情,或者也可能有一个CalendarUtils 🙂

编辑

包括开始和结束date可能不可能,如果你的间隔不完美:)

 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 } 

随着乔达时代 ,也许是更好的:

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

这是我的解决scheme….非常简单:)

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

推荐datestream

在Java-9 (可能会在2017年发布)中,您可以使用以下新方法:

 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(...)与独家结束date,因此显示的黑客添加一天。

一旦你获得了stream,你可以利用java.util.stream或者java.util.function packages提供的所有特性。 与早期的基于自定义for循环或while循环的方法相比,使用stream很简单。


或者,如果你寻找一个基于stream的解决scheme,默认情况下运行包含date,但也可以configuration,否则,你可能会发现在我的库Time4J有趣的类DateInterval类,因为它提供了很多围绕datestream的特殊function,包括一个性能分割器这比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()); 

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

尾recursion版本:

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

增强以上解决scheme之一。 添加1天到结束date有时会在结束date之后增加额外的一天。


    公共静态列表getDaysBetweenDates(date开始date,date结束date)
     {
         List dates = new ArrayList();
        日历startDay =新的GregorianCalendar();
         calendar.setTime(开始date);
        日历endDay = new GregorianCalendar();
         endDay.setTime(结束date);
         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结果= startDay.getTime();
             dates.add(结果);
             startDay.add(Calendar.DATE,1);
         }
        返回date;
     }

这是我在两个date之间获取date的方法,包括/ wo包括工作日。 它也需要源和期望的date格式作为参数。

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

你可以find演示代码: 点击这里

用java 8

 public Stream<LocalDate> getDaysBetween(LocalDate startDate, LocalDate endDate) { return IntStream.range(0, (int) DAYS.between(startDate, endDate)).mapToObj(startDate::plusDays); } 
 List<LocalDate> totalDates = new ArrayList<>(); popularDatas(startDate, endDate, totalDates); System.out.println(totalDates); private void popularDatas(LocalDate startDate, LocalDate endDate, List<LocalDate> datas) { if (!startDate.plusDays(1).isAfter(endDate)) { popularDatas(startDate.plusDays(1), endDate, datas); } datas.add(startDate); } 

recursion解决scheme

这是获取date列表的简单解决scheme

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