2

I have two dates in Java:

Wed Jan 05 00:00:00 CET 2011
Sat Jan 15 23:59:59 CET 2011

Now I want to iterate over them, so that every day I can do a System.out.println() in which I put the date in this kind on the console:

2011-01-05
2011-01-06
2011-01-07
...
2011-01-13
2011-01-14
2011-01-15

How can I do this?

Best Regards, Tim.

Update:

Calendar calend = Calendar.getInstance();
calend.setTime(myObject.getBeginDate());
Calendar beginCalendar = new GregorianCalendar(calend.get(Calendar.YEAR), calend.get(Calendar.MONTH), calend.get(Calendar.DATE));
calend.setTime(myObject.getEndDate());
Calendar endCalendar = new GregorianCalendar(calend.get(Calendar.YEAR), calend.get(Calendar.MONTH), calend.get(Calendar.DATE));
while (beginCalendar.compareTo(endCalendar) <= 0) {
     // ... calculations
    beginCalendar.add(Calendar.DATE, 1);
}
Tim
  • 13,228
  • 36
  • 108
  • 159
  • 2
    Did you take a look at http://stackoverflow.com/questions/1174899/java-joda-time-implement-a-date-range-iterator ? – DerMike Jan 05 '11 at 16:00

2 Answers2

3

Use the GregorianCalendar object to increment one day at a time

Output using SimpleDateFormat.

To get your date from a string, into a Date object, you have to do the following

SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date date = format.parse(yourDateString);

Then, you need to convert into a GregorianCalendar, so that you can easily increment the values and finally output the date using another SimplerDateFormat in the way you want to. See the documentation for the different codes.

Update: Update, following your code update, you can simply do the following

Calendar beginCalendar = Calendar.getInstance();
beginCalendar.setTime(myObject.getBeginDate());
Calendar endCalendar = Calendar.getInstance();
beginCalendar.setTime(myObject.getEndDate());


while (beginCalendar.compareTo(endCalendar) <= 0) {
     // ... calculations
    beginCalendar.add(Calendar.DATE, 1);
}
Codemwnci
  • 54,176
  • 10
  • 96
  • 129
  • Sorry, no homework, I do not know how can I put this `Wed Jan 05 00:00:00 CET 2011` into a Date object. – Tim Jan 05 '11 at 16:08
  • In my question post, I put the solution which works. Is this okay? – Tim Jan 06 '11 at 09:02
  • Yes, your solution looks fine. Although, I generally prefer to use Calendar.DAY_OF_MONTH rather than Calendar.DATE to get the DAY part of a date. They give the same value, but I find DAY_OF_MONTH more descriptive, as DATE is somewhat misleading. Also, if you already have a Date object, then you can create your GregorianCalendar and just set the time. I will update my answer to reflect. – Codemwnci Jan 06 '11 at 12:40
1

Create a Calendar object and set it at the start date. Keep adding a day at a time and printing until you're at the end date.

Qwerky
  • 18,217
  • 6
  • 44
  • 80