问题
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierISO8601];
[calendar setTimeZone:[NSTimeZone defaultTimeZone]];
[calendar setFirstWeekday:2];
[calendar setMinimumDaysInFirstWeek:1];
NSDateComponents *mockTodayComponents = [[NSDateComponents alloc] init];
mockTodayComponents.day = 28;
mockTodayComponents.month = 12;
mockTodayComponents.year = 2015;
NSDate *date = [calendar dateFromComponents:mockTodayComponents];
NSDateComponents *c = [calendar components:NSCalendarUnitWeekOfYear | NSCalendarUnitYearForWeekOfYear fromDate:date];
NSInteger week = [c weekOfYear];
week returns 1 instead of 53 and ofcoaurse the next year weeks enumeration wrong also because of it, what's wrong with my code or it's Apple's bug?
回答1:
Your minimumDaysInFirstWeek
is 1. That means that any week that has at least 1 day in the new year is the 1st week of that year. Docs
According to ISO:
There are mutually equivalent descriptions of week 01:
the week with the year's first Thursday in it (the formal ISO definition), the week with 4 January in it, the first week with the majority (four or more) of its days in the starting year, and the week starting with the Monday in the period 29 December – 4 January.
来源:https://stackoverflow.com/questions/34249588/nsdatecomponents-weekofyear-returns-wrong-value