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

I need a list of dates between the start date and the end date.

The result should be a list of all dates, including the start and end dates.

+60
java date
Apr 22 '10 at 8:53
source share
22 answers

Back in 2010, I suggested using Joda-Time for this.

Please note that Joda-Time is currently in maintenance mode. Starting with java.time 1.8 (2014), you should use java.time .

Add one day at a time until the end date is reached:

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

For this it will not be difficult to implement your own iterator, it would be even better.

+46
Apr 22 '10 at 9:10
source share

java.time package

If you are using Java 8 , there is a cleaner approach. The new java.time package in Java 8 includes Joda-Time API functions.

Your claim can be resolved using the code below:

 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); } 
+39
May 29 '14 at 12:07
source share

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; } 
+38
May 23 '10 at 22:41
source share

Streams

Change: Joda-Time is now deprecated, changed the response to using Java 8 instead.

Here is the Java 8 way using threads.

 List<LocalDate> daysRange = Stream.iterate(startDate, date -> date.plusDays(1)).limit(numOfDays).collect(Collectors.toList()); 
+18
Mar 09 '16 at 13:24
source share

Find the code below.

 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 ... 08/27/2010
Date ... 08/28/2010
Date ... 08/29/2010
Date ... 08/30/2010
Date ... 08/31/2010
Date ... 01/09/2010
Date ... 09/02/2010

+13
Aug 26 '10 at 18:20
source share

Data Stream Recommendation

In Java 9, you can use the following new method: 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()); 

The new datesUntil(...) method works with an exceptional end date, so the hack shown is for adding a day.

After you receive the stream, you can use all the functions offered by java.util.stream - or java.util.function -packages. Working with streams has become so simple compared to previous approaches based on setting for- or while-loops.




Or if you are looking for a stream-based solution that is turned on by inclusive dates by default, but can also be configured differently, you might find the DateInterval class in my Time4J library interesting because it offers many special functions in date streams, including an execution delimiter which faster than in 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); 

Or even simpler in the case of full months:

 Stream<PlainDate> februaryDates = CalendarMonth.of(2017, 2).streamDaily(); List<LocalDate> list = februaryDates.map(PlainDate::toTemporalAccessor).collect(Collectors.toList()); 
+4
Feb 20 '17 at 12:08
source share

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; } 
+3
Jul 25 '13 at 12:12
source share

With Lamma, it looks like this in Java:

  for (Date d: Dates.from(2014, 6, 29).to(2014, 7, 1).build()) { System.out.println(d); } 

and output:

  Date(2014,6,29) Date(2014,6,30) Date(2014,7,1) 
+3
Jun 10 '14 at
source share

One solution would be to create an instance of Calendar and start the loop by incrementing it with Calendar.DATE until it reaches the desired date. In addition, at each step, you must create an instance of Date (with the appropriate parameters) and put it in your list.

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; } 
+2
Apr 22 2018-10-22T00:
source share
  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; } 
+2
Nov 25 '16 at 5:58
source share

Since java 8

 public Stream<LocalDate> getDaysBetween(LocalDate startDate, LocalDate endDate) { return IntStream.range(0, (int) DAYS.between(startDate, endDate)).mapToObj(startDate::plusDays); } 
+2
Dec 06 '16 at 20:56
source share

You can also look at the Date.getTime () API. This gives you a long term in which you can add your gain. Then create a new 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; } 

and maybe apache commons have something similar in DateUtils, or maybe they have CalendarUtils :)

EDIT

including start and end may not be possible if your interval is not perfect :)

+1
Apr 22 '10 at 9:09
source share

With Joda-Time , maybe this is better:

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

This is my solution .... very simple :)

+1
Apr 18 '13 at 11:06 on
source share
 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 } 
+1
May 20 '13 at 9:36
source share

Like @folone but right

 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; } 
+1
Jul 09 '13 at 12:22
source share

Recursive version:

 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); } } 
0
Oct 24 '14 at 14:10
source share

Strengthening one of the above solutions. Since adding from 1 day to the end sometimes adds an extra day for the end date.

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

0
Feb 03 '15 at 10:24
source share

Here is my method of getting dates between two dates, including / wo including business days. It also accepts the original and desired date format as a parameter.

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

And the method call will look like this:

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

You can find the demo code: Click here.

0
Jul 14 '15 at 5:49
source share
 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); } 

Recursive solution

0
Feb 23 '17 at 11:20
source share

This is a simple solution to get a date list.

 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; } } 
0
Jul 16 '17 at 16:50
source share

This will add all the dates between the two dates and add the current dates, and then new dates will be added based on the condition of the cycle.

 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; } 
0
Nov 21 '17 at 12:45
source share

Java9 functions you can calculate as follows

 public List<LocalDate> getDatesBetween ( LocalDate startDate, LocalDate endDate) { return startDate.datesUntil(endDate) .collect(Collectors.toList()); } '' 
0
Sep 20 '19 at
source share



All Articles