Date and Time

How to Get a list of Dates between Two Dates in Java

Table of Contents

Program

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class DateBetweenTwoDates 
{
	public static void main(String[] args)
	{
		List<Date> dates = new ArrayList<Date>();
		String str_date = "27/08/2018";
		String end_date = "22/09/2018";
		DateFormat formatter;
		formatter = new SimpleDateFormat("dd/MM/yyyy");
		Date startDate = null;
		try 
		{
			startDate = (Date) formatter.parse(str_date);
		} catch (ParseException e) 
		{

			e.printStackTrace();
		}
		Date endDate = null;
		try 
		{
			endDate = (Date) formatter.parse(end_date);
		} catch (ParseException e) 
		{

			e.printStackTrace();
		}
		long interval = 24 * 1000 * 60 * 60;
		long endTime = endDate.getTime();
		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/2018
 Date is ...28/08/2018
 Date is ...29/08/2018
 Date is ...30/08/2018
 Date is ...31/08/2018
 Date is ...01/09/2018
 Date is ...02/09/2018
 Date is ...03/09/2018
 Date is ...04/09/2018
 Date is ...05/09/2018
 Date is ...06/09/2018
 Date is ...07/09/2018
 Date is ...08/09/2018
 Date is ...09/09/2018
 Date is ...10/09/2018
 Date is ...11/09/2018
 Date is ...12/09/2018
 Date is ...13/09/2018
 Date is ...14/09/2018
 Date is ...15/09/2018
 Date is ...16/09/2018
 Date is ...17/09/2018
 Date is ...18/09/2018
 Date is ...19/09/2018
 Date is ...20/09/2018
 Date is ...21/09/2018
 Date is ...22/09/2018

Description

public Date parse(String source)
throws ParseException

Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string.
See the parse(String, ParsePosition) method for more information on date parsing.

Parameters:

source – A String whose beginning should be parsed.

Returns:

A Date parsed from the string.

Throws:

ParseException – if the beginning of the specified string cannot be parsed.

public long getTime()

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

Returns:

the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this date