Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find week of the month

Tags:

java

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);
like image 615
user1686408 Avatar asked Sep 21 '12 10:09

user1686408


People also ask

What week of the month is it?

Week 43. Week 43 is from Monday, October 24, 2022 until (and including) Sunday, October 30, 2022.

How do you find weeks?

Count the number of days in the month and divide that number by 7, which is the number of days in one week. For example, if March has 31 days, there would be a total of 4.43 weeks in the month.


1 Answers

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
like image 86
Keppil Avatar answered Nov 14 '22 22:11

Keppil