Calendar.getActualMaximum(Calendar.DAY_OF_MONTH)总共返回31

时间:2015-01-08 15:45:35

标签: android calendar android-calendar

我有这个代码来计算用户选择的月份的前一个月的最后一天。变量monthNumber为我提供了选择我的用户的月份:

        lastDayOfPreviousMonth.set(Calendar.YEAR, year);
        lastDayOfPreviousMonth.set(Calendar.MONTH, monthNumber-1);
        lastDayOfPreviousMonth.set(Calendar.DAY_OF_MONTH , lastDayOfPreviousMonth.getActualMaximum(Calendar.DAY_OF_MONTH));

问题是lastDayOfPreviousMonth.getActualMaximum(Calendar.DAY_OF_MONTH));总是赐给我。¿为什么?

感谢

2 个答案:

答案 0 :(得分:0)

这不是获取上个月最大天数的合适方法。请尝试以下方法:

calendarPreviousMonth.add(Calendar.MONTH, -1);

答案 1 :(得分:0)

我已经验证了您的程序,只需添加必要的声明和格式输出:

GregorianCalendar lastDayOfPreviousMonth = new GregorianCalendar(2012, 2, 1);
int month = 5; // May (here 1-based month)

lastDayOfPreviousMonth.set(Calendar.YEAR, 2015);
// 2 for one-based month-input and previous month
lastDayOfPreviousMonth.set(Calendar.MONTH, month - 2);
lastDayOfPreviousMonth.set(
    Calendar.DAY_OF_MONTH,
    lastDayOfPreviousMonth.getActualMaximum(Calendar.DAY_OF_MONTH)
);

System.out.println(lastDayOfPreviousMonth.getActualMaximum(Calendar.DAY_OF_MONTH)); 
// output: 30

System.out.println(DateFormat.getDateInstance().format(lastDayOfPreviousMonth.getTime()));
// output: 30.04.2015

它对我有用。也许您应该检查初始化和/或在Dalvik VM上使用此示例代码。