Question

Contrary to what I expected setting the weekOfMonth property from an NSDateComponents object does not have an effect on weekOfYear...

NSDateComponents *iterativeComponents = [calendar components:   NSYearCalendarUnit|
                                                                        NSMonthCalendarUnit|
                                                                        NSWeekOfYearCalendarUnit|
                                                                        NSWeekOfMonthCalendarUnit|
                                                                        NSWeekdayCalendarUnit
                                                            fromDate:referenceDate];

for (int j = 4; j > -1; j--) {
    iterativeComponents.weekOfMonth = j;
    NSDate *dateForWeek = [calendar dateFromComponents:iterativeComponents];
}

Setting the weekOfMonth of iterativeComponents does not change the weekOfYear and leaves me with an inconsistent NSDateComponents object:

<NSDateComponents: 0x9aac9e0>
Calendar Year: 2012
Month: 9
Leap month: no
Week of Year: 36
Week of Month: 3
Weekday: 2

A quick check in the calendar tells me that the third week of September 2009 is the 37th week of the year. The date generated of iterativeComponents is

2012-09-02 22:00:00 +0000

How can I achieve the correct calculation of the weekOfYear property by setting the weekOfMonth?

Was it helpful?

Solution

NSDateComponents is only a simple container for its elements. The magic happens in NSCalendar's methods that calculate NSDate objects.

So convert the components to a proper date and than back to an NSDateComponents.

Since you can't calculate the week of year from a year, month and weekOfMonth (there are usually two week-of-years in one week-of-month) you have to select a day for which to check, for example monday.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top