1

I am using calendar.getActualMaximum(Calendar.WEEK_OF_YEAR) to get total number of weeks in a given year. This is the function I am using :

public static void main(String[] args) {

    for(int i=2012; i<=2016; i++) {
        System.out.println("Year : " + i + ", Total Weeks : " + getNumWeeksForYear(i));
    }

}
public static int getNumWeeksForYear(int year) {  
    Calendar c = Calendar.getInstance();           
    c.set(year, 12, 31); //issue
    c.setFirstDayOfWeek(Calendar.MONDAY );
    return c.getActualMaximum(Calendar.WEEK_OF_YEAR);   
}
Output with c.set(year, 12, 31): 
Year : 2012, Total Weeks : 52
Year : 2013, Total Weeks : 52
Year : 2014, Total Weeks : 52
Year : 2015, Total Weeks : 52
Year : 2016, Total Weeks : 53
Output with c.set(year, 1, 31): 
Year : 2012, Total Weeks : 53
Year : 2013, Total Weeks : 52
Year : 2014, Total Weeks : 52
Year : 2015, Total Weeks : 52
Year : 2016, Total Weeks : 52

I am unable to figure it out why the total weeks in a year are different when the calendar month is set to Dec. I have tried using months 1-12, for 1-11 the number of weeks are same but changes for the month 12. From the experiment I can predict it only happens with leap years.

I had referred the following link: Calendar.getActualMaximum(Calendar.WEEK_OF_YEAR) weirdness

But this does not answer my query.

Community
  • 1
  • 1
Monish Kamble
  • 1,478
  • 1
  • 15
  • 28

2 Answers2

2

The first month is

private static final int JANUARY = 0;

and the last month is

private static final int DECEMBER = 11;

This means that month 12 is the first month of the next year.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • @Peter : Thanks. You are correct. But if I use 11(Dec of current month 2016), it returns 52 weeks whereas 2016 has 53 weeks. What is the correct way to get the total number of weeks? – Monish Kamble Apr 06 '16 at 13:01
1

Here months index starts form 0 like this.

JANUARY=0, FEBRUARY=1,.., DECEMBER=11

So till 11 it will return correct values

Example code:

public static int getNumWeeksForYear(int year) {  
        Calendar c = Calendar.getInstance();           
        c.set(year, 11,31); //issue
        c.setFirstDayOfWeek(Calendar.MONDAY );
        return c.getActualMaximum(Calendar.WEEK_OF_YEAR);   
    }

output:

Year : 2012, Total Weeks : 53
Year : 2013, Total Weeks : 52
Year : 2014, Total Weeks : 52
Year : 2015, Total Weeks : 52
Year : 2016, Total Weeks : 52

If you give grater than 11

c.set(year, 14,31);

output:

Year : 2012, Total Weeks : 52
Year : 2013, Total Weeks : 52
Year : 2014, Total Weeks : 52
Year : 2015, Total Weeks : 52
Year : 2016, Total Weeks : 53

to calculate accurate weeks in a year see this example

Community
  • 1
  • 1
Venu
  • 348
  • 4
  • 17