I am not sure whether you want to return an array of length equal to the number of days in the month, with each value being the week number for the corresponding day, or an array of all distinct week numbers for the days in the specified month. Assuming it is the former, this should work:
public static int[] getWeeksOfMonth(int month, int year)
{
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, 1);
int ndays = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
int weeks[] = new int[ndays];
for (int i = 0; i < ndays; i++)
{
weeks[i] = cal.get(Calendar.WEEK_OF_YEAR);
cal.add(Calendar.DATE, 1);
}
return weeks;
}
If you want an array of distinct week numbers for the days in the specified month:
public static Integer[] getWeeksOfMonth(int month, int year)
{
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, 1);
Set<Integer> weeks = new HashSet<Integer>();
int ndays = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
for (int i = 0; i < ndays; i++)
{
weeks.add(cal.get(Calendar.WEEK_OF_YEAR));
cal.add(Calendar.DATE, 1);
}
return weeks.toArray(new Integer[0]);
}
(Note this last example returns an array of Integer
objects, but it is trivial to modify it to return an array of int
instead)