Here's my code:
Calendar c = new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.set(Calendar.WEEK_OF_YEAR, selectedWeek);
c.set(Calendar.YEAR, selectedYear);
Log.v(FILE_NAME,"C content: " + c.toString());
int firstDayOfWeek = c.getFirstDayOfWeek();
String[] days = new String[firstDayOfWeek + 7];
for (int i = firstDayOfWeek; i < firstDayOfWeek + 7; i++) {
c.set(Calendar.DAY_OF_WEEK, i);
days[i] = new SimpleDateFormat("d MMM").format(c.getTime());
}
Log.v(FILE_NAME, "Start " + days[firstDayOfWeek] + " to " + days[firstDayOfWeek + 6]);
I set selectedWeek to 51, selectedYear to 2016. So my expectation was, since I already gave the week and year, in my last Log.v, I should be getting the list of dates in the given week (51), which is 19 Dec to 25 Dec. Instead I'll always get the dates in the current week (for example, currently I will always get 12 Dec to 18 Dec)
Displaying the contents of c gives me
java.util.GregorianCalendar[time=?,areFieldsSet=false,lenient=true,zone=Asia/Kuala_Lumpur,firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2016,MONTH=11,WEEK_OF_YEAR=52,WEEK_OF_MONTH=3,DAY_OF_MONTH=18,DAY_OF_YEAR=353,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=1,HOUR_OF_DAY=1,MINUTE=24,SECOND=46,MILLISECOND=30,ZONE_OFFSET=28800000,DST_OFFSET=0]
It seems WEEK_OF_MONTH returns the CURRENT WEEK_OF_MONTH, not of the given selectedWeek and selectedYear. Same goes to DAY_OF_MONTH. My assumption was the DAY_OF_MONTH should at least return the starting date of the given selectedWeek?
Did I understand wrongly? If I did, what should I do so that days[firstDayOfWeek] returns the first day in the given the week and year?
I think I figured out the problem. The thing is when you set
Calendar.DAY_OF_WEEK
, the calendar resets itself and just change the day of week to what you are setting it. So to make your code work, you have to setCalendar.WEEK_OF_YEAR
inside the for loop.