javaandroidloopscalendargregorian-calendar

Calendar day of month Android


I choose the starting date (example 31/01/2014) and ending date (example 31/12/2014), I insert a record every month. If I get the next month is February 28th, but then I always get 28 though March, April, etc. .. How can I fix? I hope I explained

SimpleDateFormat sdf1 = new SimpleDateFormat( "yyyy-MM-dd" );
ContentValues cv = new ContentValues();

for(
  int i=0; 
  calendar1.getTime().before(calendar2.getTime()); 
  i++
) {
  calendar1.add(Calendar.MONTH, 1);

  if (calendar1.getTime().before(calendar2.getTime())) {
    String strDate = sdf1.format(calendar1.getTime());
    cv.put(etableTable.DATE, strDate);  
    db.insert(etableTable.TABLE_NAME, null, cv);
    ...
  }
}

Solution

  • Assuming that you speak about class GregorianCalendar - Instead of calendar1.add(Calendar.MONTH, 1) try to also call following method as work-around:

    static GregorianCalendar moveToEndOfMonth(GregorianCalendar gcal) {
      gcal.add(Calendar.MONTH, 1); // moving to some day of next month
      gcal.set(Calendar.DAY_OF_MONTH, 1); // moving to first day of current month
      gcal.add(Calendar.DATE, -1); // moving to last day of previous month
    }
    

    So your final code should look like:

    calendar1.add(Calendar.MONTH, 1);
    moveToEndOfMonth(calendar1);
    

    Why? The analysis of @DavidCAdams is right, see his answer.