Android 向日历添加月份的问题

Android issue adding months to calendar

我将 3 个月添加到日历实例以获取三个月的所有日期。当所有三个月都在同一年时,它工作正常。我将设备的月份更改为 11 月,应用程序挂起并崩溃。这是我的代码。

private void GenerateData() {
    Calendar today = Calendar.getInstance();
    today.set(Calendar.DAY_OF_MONTH,1);
    month = today.get(Calendar.MONTH);
    System.out.println("this month "+today.getTime());
    Calendar cal = Calendar.getInstance();
    System.out.println("Before "+cal.getTime());  
    if(count<=(month-11))
        cal.add(Calendar.MONTH, count);
    else{
        cal.add(Calendar.YEAR, 1);
        cal.add(Calendar.MONTH, 1);
    }
    System.out.println("After "+cal.getTime());

    while (today.getTime().before(cal.getTime()))
    {
        List<Date> date = new ArrayList<Date>();
        if(today.get(Calendar.MONTH)==month){
            System.out.println("Dates of month "+month);
        }else{
            month++;
            System.out.println("Dates of month "+month);
        }
        while(today.get(Calendar.MONTH)==month) {
            Date result = today.getTime();
            //System.out.println(result);
            date.add(result);
            today.add(Calendar.DATE, 1);
        }

        list.add(date);
    }
}

你得到一个无限循环:

while (today.getTime().before(cal.getTime()))
{
    // ...
        month++;

    while(today.get(Calendar.MONTH)==month) {
     // ...
        today.add(Calendar.DATE, 1);
    }

}

如果month是11,month++是12,第二个while循环永远不会执行(月份只有0...11),today不是递增并且外循环永远重复(或直到 month 溢出并再次到达 today 的月份...)。

month = (month+1) % 12 而不是 month++ 应该可以解决问题。

另一种解决方案是确保 today 次迭代中真正递增,例如:

while (today.getTime().before(cal.getTime()))
{

  month = today.get(Calendar.MONTH);

  do {
    today.add( Calendar.DATE, 1 );
    date.add(today.getTime());
  } while ( today.get(Calendar.MONTH) == month );

}

将日历设置为,

    Calendar today = Calendar.getInstance();
    today.set(Calendar.DAY_OF_MONTH,1 );

并根据需要将月份 1 增加 1,

 today.add(Calendar.MONTH, j); 

计算最大值。月份中的日期,例如

int daysInMonth = today.getActualMaximum(Calendar.DAY_OF_MONTH);

然后获取月中的日期,例如,

 for (int i = 0; i < daysInMonth; i++) 
 {
    Log.e("dateTag", today.getTime());

    today.add(Calendar.DAY_OF_MONTH, 1);
 } 

增加循环j,你将得到接下来的几个月。

您对 Calendar 对象的理解有误。 如果你想给一个对象加三个月,就给这个对象加三个月。

Calendar calendar = Calendar.getInstance();
calendar.set(2014, 10, 11); // This means 2014/Nov/11

Calendar future = (Calendar) calendar.clone();
future.add(Calendar.MONTH, 3); // This means 2015/Feb/10

while (calendar.before(future)) {
    System.out.println(calendar.get(Calendar.YEAR) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + calendar.get(Calendar.DAY_OF_MONTH));

    calendar.add(Calendar.DATE, 1);
}

请注意日历对象的一月(一年中的第一个月)是 0