[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 598
  • Last Modified:

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

0
buckrodger
Asked:
buckrodger
  • 2
  • 2
1 Solution
 
Thomas4019Commented:
The line

now.set(Calendar.DAY_OF_MONTH, now.getMaximum(Calendar.DAY_OF_MONTH));

does not function as your want because of the getMaximum is designed to return the maximum day for any month and not this month specifically.

You should be using getActualMaximum(Calendar.DAY_OF_MONTH)
0
 
buckrodgerAuthor Commented:
The documentation of that is unclear, what is the difference ???

thanks
0
 
buckrodgerAuthor Commented:
thank you
0
 
Thomas4019Commented:
"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.
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now