File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Calendar : getting week of month Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Calendar : getting week of month" Watch "Calendar : getting week of month" New topic

Calendar : getting week of month

Gouri Bargi
Ranch Hand

Joined: Sep 29, 2002
Posts: 47
I want to get the dates for a particular week in a month.
I am trying to use set(Calendar.WEEK_OF_MONTH) and it is giving me strange results. Here is the code:

The output is
Fri Mar 12 10:50:59 GMT+05:30 2004
As 1st March 2003 is a Monday, the next week date I am expecting is 8th march. Can anyone help?
Rene Larsen
Ranch Hand

Joined: Oct 12, 2001
Posts: 1179

You can try change 'date.set(Calendar.WEEK_OF_MONTH, 2);' to: 'date.add(Calendar.WEEK_OF_MONTH, 1);' witch add one week to the current Date.

Regards, Rene Larsen
Dropbox Invite
Gouri Bargi
Ranch Hand

Joined: Sep 29, 2002
Posts: 47
Thanks Rene. It works. Meanwhile, I came across another alternative - if I modify the code as following, it works:

And another alternative - If I add a call to
date.get(Calendar.WEEK_OF_MONTH) before setting the week of month, I get the desired output:

Is this a bug?
Eddie Vanda
Ranch Hand

Joined: Mar 18, 2003
Posts: 281
You could try the "complete ()" method before using the values. From the api docco:

protected void complete();
Fills in any unset fields in the calendar fields. First, the computeTime() method is called if the time value (millisecond offset from the Epoch) has not been calculated from calendar field values. Then, the computeFields() method is called to calculate all calendar field values.

[ March 12, 2004: Message edited by: Eddie Vanda ]

The nice thing about Standards is that there are so many to choose from!
I agree. Here's the link:
subject: Calendar : getting week of month
jQuery in Action, 3rd edition