D3X D3X - 5 months ago 20
Java Question

Date List Increment Method in Java

Okay, So here is the question, I am trying to make a method, which helps me put all the dates from date A to date B in a list and place the day type in front of it for example:
Date A- 01 JAN 2013 Date B-03 JAN 2013

The result should be like this

01-01-2013 Tuesday

02-01-2013 Wednesday

03-01-2013 Thursday

And this should be either in a Map/List.

I tired the following approach to first at least have the dates in the list, but got a Java Out of Heap Space Error.

public static List<ShiftDate> createShiftDate() {
String startDate = "2013-01-01";

String lastDate = "2013-01-28";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
List<ShiftDate> shiftDateList = new ArrayList<ShiftDate>();
ShiftDate shiftDate = new ShiftDate();

try {
Date startDate1 = formatter.parse(startDate);
Date endDate1 = formatter.parse(lastDate);
Calendar c = Calendar.getInstance();
Date newDate = startDate1;

while (newDate.compareTo(endDate1) < 0) {
c.setTime(newDate);
c.add(Calendar.DATE, 1);
shiftDate.setDateString(c.getTime().toString());
shiftDateList.add(shiftDate);
}

} catch (ParseException e) {
e.printStackTrace();
}
for (ShiftDate shiftDate1 : shiftDateList) {
System.out.println(shiftDate1);
}
return shiftDateList;
}

Answer
  1. You are not updating the loop condition variable (newDate). It should look like this:

        while (newDate.compareTo(endDate1) < 0) {
            c.setTime(newDate);
            c.add(Calendar.DATE, 1);
            newDate = c.getTime();
            shiftDate.setDateString(c.getTime().toString());
            shiftDateList.add(shiftDate);
        }
    
  2. Other problems: you have the formatter set to dd-MM-yyyy patter, but the actual dates are in yyyy-MM-dd pattern.

  3. Also, you'll need to create a new instance of ShiftDate each time or else each time. Or else you will end up with the entire listing containing the same (last updated) date value.

        while (newDate.compareTo(endDate1) < 0) {
            c.setTime(newDate);
            c.add(Calendar.DATE, 1);
            newDate = c.getTime();
            shiftDate = new ShiftDate();
            shiftDate.setDateString(c.getTime().toString());
            shiftDateList.add(shiftDate);
        }