views:

318

answers:

4

I have the start date and the end date. I need to iterate through every day between these 2 dates.

What's the best way to do this?

I can suggest only something like:

Date currentDate = new Date (startDate.getTime ());
while (true) {
   if (currentDate.getTime () >= endDate.getTime ())
      break;
   doSmth ();
   currentDate = new Date (currentDate.getTime () + MILLIS_PER_DAY);
}
+2  A: 

Use a Calendar object if you want to manipulate dates.

    Calendar c = Calendar.getInstance();
    // ... set the calendar time ...
    Date endDate = new Date();
    // ... set the endDate value ...

    while (c.getTime().before(endDate) {
       // do something
       c.add(Calendar.DAY_OF_WEEK, 1);
    }

Or use Joda Time

Jherico
+2  A: 

ready to run ;-)

public static void main(String[] args) throws ParseException {
    GregorianCalendar gcal = new GregorianCalendar();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
    Date start = sdf.parse("2010.01.01");
    Date end = sdf.parse("2010.01.14");
    gcal.setTime(start);
    while (gcal.getTime().before(end)) {
        gcal.add(Calendar.DAY_OF_YEAR, 1);
        System.out.println( gcal.getTime().toString());
    }
}
stacker
+1  A: 

Ditto on those saying to use a Calendar object.

You can get into surprising trouble if you try to use a Date object and add 24 hours to it.

Here's a riddle for you: What is the longest month of the year? You might think that there is no answer to that question. Seven months have 31 days each, so they are all the same length, right? Well, in the United States that would be almost right, but in Europe it would be wrong! In Europe, October is the longest month. It has 31 days and 1 hour, because Europeans set their clocks back 1 hour for Daylight Saving Time in October, making one day in October last 25 hours. (Americans now begin DST in November, which has 30 days, so November is still shorter than October or December. Thus making that riddle not as amusing for Americans.)

I once ran into trouble by doing exactly what you're trying to do: I used a Date object and added 24 hours to it in a loop. It worked as long as I didn't cross Daylight Saving Time boundaries. But when I did, suddenly I skipped a day or hit the same day twice, because Midnight March 8, 2009 + 24 hours = 1:00 AM March 10. Drop off the time, as I was doing, and March 9 was mysteriously skipped. Likewise midnight Nov 1, 2009 + 24 hours = 11:00 PM Nov 1, and we hit Nov 1 twice.

Jay
thanks for your addition
Roman