NSDateComponents weekOfYear returns wrong value

别来无恙 提交于 2019-12-02 03:38:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!