简体   繁体   中英

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);
    ...
  }
}

Where are you creating the calendar objects? Since you are incrementing the MONTH, and it is January 30, you get February 28 for the next month, since next month only has 28 days in it. There is no Feb 30, 2014. Thereafter, when you increment the month, you get March 28, April 28, etc. etc.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM