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);
Week 43. Week 43 is from Monday, October 24, 2022 until (and including) Sunday, October 30, 2022.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With