2

I am getting issue while fetching WEEK_OF_YEAR from calendar object.

by passing date '31-Dec-2014':
calendar1.get(Calendar.WEEK_OF_YEAR) - return 1  

by passing date '31-Dec-2015'  
calendar1.get(Calendar.WEEK_OF_YEAR) - return  53  

by passing date '31-Dec-2016'   
calendar1.get(Calendar.WEEK_OF_YEAR) - return 52

by passing date '31-Dec-2017'  
calendar1.get(Calendar.WEEK_OF_YEAR) - return 52  

by passing date '31-Dec-2018'   
calendar1.get(Calendar.WEEK_OF_YEAR) - return 1  

Every time it returns different value . Could you please help me to solve this issue.

code is as below.

  Calendar calendar1 = Calendar.getInstance();
  calendar1.setTime('31-Dec-2012');
  calendar1.set(Calendar.HOUR_OF_DAY, 0);
  calendar1.setFirstDayOfWeek(Calendar.MONDAY);
Kuf
  • 17,318
  • 6
  • 67
  • 91

2 Answers2

2

WEEK_OF_YEAR definition is Locale dependent as you can see in this javadoc :

Values calculated for the WEEK_OF_YEAR field range from 1 to 53. The first week of a calendar year is the earliest seven day period starting on getFirstDayOfWeek() that contains at least getMinimalDaysInFirstWeek() days from that year. It thus depends on the values of getMinimalDaysInFirstWeek(), getFirstDayOfWeek(), and the day of the week of January 1. Weeks between week 1 of one year and week 1 of the following year (exclusive) are numbered sequentially from 2 to 52 or 53 (except for year(s) involved in the Julian-Gregorian transition).

also have a look at this question or at Wiki - ISO clock to see the week difference.

Kuf
  • 17,318
  • 6
  • 67
  • 91
1

it's dupped question but long story short

Calendar c = Calendar.getInstance();
c.setMinimalDaysInFirstWeek(7);//anything more than 1 will work in this year
DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
c.setTime( sdf.parse("31/12/2010"));
System.out.println( c.get( Calendar.WEEK_OF_YEAR ) );

return 53 for 31-dec-2012