I just wanna ask what is the efficient way to get the week numbers of a certain month. I have a function with month number & year as arguments, the return value of the function should be a int array which contain the week numbers of the specific month.(like following...)
public int[] getWeeksOfMonth(int month, int year){
//what's the efficient way to implement this??
}
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:
If you want an array of distinct week numbers for the days in the specified month:
(Note this last example returns an array of
Integer
objects, but it is trivial to modify it to return an array ofint
instead)Calendar cal = Calendar.getInstance();
int maxWeeknumber = cal.getActualMaximum(Calendar.WEEK_OF_MONTH);
get(Calendar.WEEK_OF_YEAR)
The
WEEK_OF_YEAR
attribute of theCalendar
class can be usefull for you.Create a new date that will be the first day of the given month. Get the week of the year for this day, let say you got
start
value.Create a new date that will be the last day of the given month. Get the week of the year for this day, so now you got
end
value.Finally, create a simple
int[]
that will contains values fromstart
toend
.I think, that this is much simpler way: