user1686408 user1686408 - 4 months ago 10
Java Question

How to find week of the month

I like to know which week of the month a particular day falls. For example 20-Sep-2012 falls on 4th week of September but the below code displays it as 3 which is not correct. The system is dividing the days by 7 and returning the output and which is not I require. I have searched in Joda API's but not able to find the solution. Please let me know is there any way to figure out the week of a month, a day falls

Calendar ca1 = Calendar.getInstance();

ca1.set(2012,9,20);

int wk=ca1.get(Calendar.WEEK_OF_MONTH);
System.out.println("Week of Month :"+wk);

Answer

This is due to two reasons:

The first one is this (from the API):

The first week of a month or year is defined as the earliest seven day period beginning on getFirstDayOfWeek() and containing at least getMinimalDaysInFirstWeek() days

The default value for this varies (mine was 4), but you can set this to your preferred value with

Calendar.setMinimalDaysInFirstWeek()

The second reason is the one @Timmy brought up in his answer. You need to perform both changes for your code to work. Complete working example:

public static void main(String[] args) {
    Calendar ca1 = Calendar.getInstance();
    ca1.set(2012, Calendar.SEPTEMBER, 20);
    ca1.setMinimalDaysInFirstWeek(1);
    int wk = ca1.get(Calendar.WEEK_OF_MONTH);
    System.out.println("Week of Month :" + wk);
}

This prints

Week of Month :4
Comments