Link to home
Start Free TrialLog in
Avatar of buckrodger
buckrodger

asked on

Calendar date arithmetic

I am doing some date arithmetic and calendar attribute setting but its not working as documented.
The code below gets a calendar, subtracts a month then its supposed to
set the last day for that month.  According to the java doc add should immediately change the value set and any dependent values in the calendar.  But when I do this on 5/2/09, I can see the the values in the calendar are month=3 and day_of_month=31. so when I call getTime I get 5/1/09.

what am I doing wrong ?


Calendar now = GregorianCalendar.getInstance();
    now.setTimeZone(TimeZone.getTimeZone("America/Denver"));
    now.add(Calendar.MONTH, -1);
    now.set(Calendar.DAY_OF_MONTH, now.getMaximum(Calendar.DAY_OF_MONTH));
    period = now.getTime();

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Thomas4019
Thomas4019
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of buckrodger
buckrodger

ASKER

The documentation of that is unclear, what is the difference ???

thanks
thank you
"getMaximum" returns the largest possible value that "get" can return. So for a month, that is always "31", even if the calendar happens to be February. "getActualMaximum" returns the largest possible value for the field that this particular calendar time can have. The way "getActualMaximum" works is by temporarily incrementing the field until it reaches the max. So "getActualMaximum" returns the actual number of days in the month of that calendar.