0

I'm stumped on this question. Is it possible to add dates before a specified date into an arraylist? No luck trying to find an answer.

This is how I intended to do it.

try {
    String format = min;
    String format2 = format.substring(0,7);
    String format3 = format.substring(7,format.length());
    String finalFormat =format2+"20"+format3;
    String finalFormatPart1 = finalFormat.substring(0, 2);
    String finalFormatPart2 = finalFormat.substring(3, 6);
    String finalFormatPart3 = finalFormat.substring(7, finalFormat.length());
    String finalFormatcomplete =finalFormatPart1+" "+finalFormatPart2+" "+finalFormatPart3;

    minDate = new SimpleDateFormat("dd MMM yyyy").parse(finalFormatcomplete);
    Log.i("minDateTime", minDate.toString());

} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Date rightNow = Calendar.getInstance().getTime();
for(int i=1; i != 31; i++) {
    Calendar calendar = Calendar.getInstance();
    calendar.add(rightNow, -i);
    beforeMin.add(dateToAdd);
}

However, calendar.add() only accepts int, int. Is there a way to add dates before my specified date into an arraylist?

codePG
  • 1,754
  • 1
  • 12
  • 19

3 Answers3

0

You can get previous date as :

calender.add(Calendar.DATE, -1);

So change your code to :

Calendar rightNow = Calendar.getInstance();
for (int i = 1; i <= 31; i++) {

    rightNow.add(Calendar.DATE, -i);
    Date dateToAdd = rightNow.getTime();
    beforeMin.add(dateToAdd);
}
SweetWisher ツ
  • 7,296
  • 2
  • 30
  • 74
0

Add the elements and sort it

Add a comparator :

Collections.sort(myList, new Comparator<MyObject>() {
  public int compare(MyObject obj1, MyObject obj2) {
      return obj1.getDateTime().compareTo(obj2.getDateTime());
  }
});

Below is the compareTo function :

 public int compareTo(MyObject obj) {
    if (getDateTime() == null || obj.getDateTime() == null)
      return 0;
    return getDateTime().compareTo(obj.getDateTime());
  }
KOTIOS
  • 11,177
  • 3
  • 39
  • 66
0

Change your code as below:

Calendar calendar = Calendar.getInstance();
for(int i=1; i < 31; i++)
{
    calendar.add(Calendar.DATE, -1);
    beforeMin.add(calendar.getTime());
}
Joey Chong
  • 1,470
  • 15
  • 20