Link to home
Start Free TrialLog in
Avatar of monitorscreen
monitorscreen

asked on

Access dates between two dates

Hi,

I have two dates:

Date From - 01/01/2008
Date To  - 4/01/2008

How can I output all of the dates between the two. So my output would be :
01/01/2008
02/01/2008
03/01/2008
04/01/2008

Thanks
Avatar of cmalakar
cmalakar
Flag of India image

Use Calendar's add() api...

Calendar obj = Calendar.getInstance();
obj.set(2001, 01, 01);
obj.add(Calendar.DATE, 1);

print the date...
you can keep on adding till you get the required date...

You can come to know the current day, month, year by using get() method of Calendar Class.
you can use the DateFormat and SimpleDateFormat for printing the date in your required format...
probably you can do this below,

Date date1 = DateFormat.getInstance().parse( "01/01/2008" ) ;
Date date2 = DateFormat.getInstance().parse( "04/01/2008" ) ;

Calendar cal1 = Calendar.getInstance();
cal1.setTime( date1 );
Calendar cal2 = Calendar.getInstance();
cal2.setTime( date2 );

while( ! isSameDay( cal1, cal2 ) ){
  //print the cal1 date here
  cal1.add( Calendar.DATE, 1 ) ;
}

public static boolean isSameDay( Calendar cal1, Calendar cal2 ){
   return cal1.get( 0 ) == cal2.get( 0 ) && cal1.get( 1 ) == cal2.get( 1 ) && cal1.get( 6 ) == cal2.get( 6 );
      }
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
expanding on what cmalakar and others have posted, to get the output you need use something like this:

DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = df.parse("01/01/2008") ;
Date date2 = df.parse("04/01/2008") ;
 
Calendar cal = Calendar.getInstance();
cal.setTime( date1 );
while(cal.getTime().before(date2) || cal.getTime().equals(date2)) {
  System.out.println(df.format(cal.getTime());
  cal.add( Calendar.DATE, 1 ) ;
}
:-)