Reputation: 171
I use the following to obtain a week number from an NSDate:
[[calendar components: NSWeekCalendarUnit fromDate:date] week]
Unfortunately, I get different values in different iOS versions. Values returned by iOS 4.* and 5 differ by 1. Is there any way to retrieve week number consistently?
Upvotes: 17
Views: 9914
Reputation: 112873
iOS5 appears to be wrong, Bug ID# 10412573.
Summary: iOS5 NSDateComponents week reports the incorrect week with both NSWeekCalendarUnit and NSWeekOfYearCalendarUnit.
Steps to Reproduce:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *date = [NSDate date];
NSLog(@"week: %i", [[calendar components: NSWeekCalendarUnit fromDate:date] week]);
NSLog(@"week: %i", [[calendar components: NSWeekOfYearCalendarUnit fromDate:date] weekOfYear]);
Expected Results: The same week number on iOS4 and iOS5. For 11/8/2011 the week should be 45.
Actual Results: The same week number on iOS5. For 11/8/2011 the week should be 46.
Regression: iOS4 is correct, iOS5 is incorrect.
Upvotes: 7
Reputation: 384
Since iOS5 NSCalender dosent seem to be defining accordingly to ISO 8601 as default. You need to set your calender with method "setMinimumDaysInFirstWeek" to get expected week number result.
[yourCalender setMinimumDaysInFirstWeek:4];
"4" means Thursday in this case.
http://en.wikipedia.org/wiki/ISO_week_date "The first week of a year is the week that contains the first Thursday of the year."
I don't know why it's not defined as "4" as default in iOS5. Just one of those wierd "bugs" i guess ;)
And yes, this will work in both iOS 4 and 5.
Upvotes: 23