hGP5b
hGP5b

Reputation: 171

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?

Upvotes: 17

Views: 9914

Answers (3)

zaph
zaph

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

David Allansson
David Allansson

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

mouviciel
mouviciel

Reputation: 67879

Week numbering is standardized by ISO 8601.

I bet that iOS5 is correct and that a bug has been filed for iOS4.

A possible solution is to add a workaround that fixes the iOS4 bug.

Upvotes: -1

Related Questions