javacalendar

How to calculate day counts of previous month?


I would like to retrieve day counts of previous month. I can get day counts of current month by

    Calendar calendar = Calendar.getInstance();
    calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), 1);
    int currentMonthDaysCount = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    System.out.println(currentMonthDaysCount);

So , I tried to get day counts of previous month as

    Calendar calendar = Calendar.getInstance();
    calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH - 1), 1);
    int previousMonthDaysCount = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    System.out.println(previousMonthDaysCount);

I got 30 at my console. What I am wrong ? This month is August and previous month July should produce 31.


Solution

  • You are subtracting from a Calendar constant instead of subtracting from the value you get from that constant.

    Change:

    calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH - 1), 1);
    

    With:

    calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) - 1, 1);
    

    Easier solution:

    calendar.roll(Calendar.MONTH, false);
    

    ... will "roll" one month "down".