How to find week of the month

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

Month is zero-based. So ca1.set(2012,9,20) is actually setting the calendar to October.

Tags:

Java