The following code calculates the previous week number from a given week when passed year and week.
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:year];
[components setWeek:NSWeekCalendarUnit];
[components setWeekOfYear:(week-1)]; //Get the previous week
[components setWeekday:2]; //Monday
[components setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [calendar dateFromComponents:components];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyyww"];
NSString *newRevision = [formatter stringFromDate:date];
I was surprised that this handled cases like 201101 (which gives 201052), but it does not correctly handle years where there are 53 weeks. For example, for 201601 it returns 201552 instead of 201153. (At least it should return 201153 according to http://en.wikipedia.org/wiki/ISO_week_date anyway.)
Am I doing something wrong? I have traced through to make sure the inputs are correct.
We ended up working around the issue with a bit of hack. From the wikipedia link in the question, we got the list of all years with 53 weeks for the next 400 years and hard coded them in (with judicious comments and the ‘correct’ solution included).
It’s not ideal, but it will do the job until either Apple implements ISO 8601 or until the year 2404.