Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a week number from NSDate consistently in all iOS versions?

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?

like image 766
hGP5b Avatar asked Nov 07 '11 14:11

hGP5b


2 Answers

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.

like image 153
David Allansson Avatar answered Nov 09 '22 18:11

David Allansson


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.

like image 38
zaph Avatar answered Nov 09 '22 18:11

zaph