Android问题为日历添加了几个月

时间:2015-01-23 12:18:00

标签: android 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);
    }
}

3 个答案:

答案 0 :(得分:1)

你得到一个无限循环:

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++应该可以解决问题。

另一个解决方案是确保{<1}}在每次迭代中真正增加,例如:

today

答案 1 :(得分:0)

将日历设为,

    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,你将获得接下来的几个月。

答案 2 :(得分:0)

您误解了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);
}

请注意日历对象&#39; 1月(一年中的第一个月) 0