Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
985 views
in Technique[技术] by (71.8m points)

objective c - NSDateComponents weekOfYear returns wrong value

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?

Check start of week 53

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...